Button not linking to java class - Java for Android App Development

Basically I created a button on my app which links it to another java class. I already setted the layout for the java class using the setContentView method.
But whenenever I click on the button, it doesn't take me to that java class. Im still practising right now but ive gone through the whole project nd couldn't find whats going wrong. I literally cant find any errors.
This is what I did to link the button:
Code:
package com.tarikh.thebasics;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class splash extends Activity{
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button tut1 = (Button) findViewById(R.id.button1);
tut1.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.tarikh.thebasics.TUTORIALONE"));
}
});
}
as you can see, the tutorialone class has the following layout:
Code:
public class TUTORIALONE extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial1);
and the tutorial1.xml layout consists of a radiobutton (this is just rough). so whenever I click on the button, it should take me to the tutorialone class right?

Try:
Code:
Intent intent = new Intent(splash.this, TUTORIALONE.class);
startActivity(intent);
TwilightLoz said:
Basically I created a button on my app which links it to another java class. I already setted the layout for the java class using the setContentView method.
But whenenever I click on the button, it doesn't take me to that java class. Im still practising right now but ive gone through the whole project nd couldn't find whats going wrong. I literally cant find any errors.
This is what I did to link the button:
Code:
package com.tarikh.thebasics;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class splash extends Activity{
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button tut1 = (Button) findViewById(R.id.button1);
tut1.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.tarikh.thebasics.TUTORIALONE"));
}
});
}
as you can see, the tutorialone class has the following layout:
Code:
public class TUTORIALONE extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial1);
and the tutorial1.xml layout consists of a radiobutton (this is just rough). so whenever I click on the button, it should take me to the tutorialone class right?
Click to expand...
Click to collapse

zalez said:
Try:
Code:
Intent intent = new Intent(splash.this, TUTORIALONE.class);
startActivity(intent);
Click to expand...
Click to collapse
Nope, that doesn't work. I don't know why but I have a feeling its something got to do with my emulator. I think its not set up right..

Is there any output from the logcat?

zalez said:
Is there any output from the logcat?
Click to expand...
Click to collapse
Nope, that's the weird thing. I think there is something wrong with the emulator since it does lag alot when I run it and also I cant use the home button, back button and the search button on the emulator...

I would start by deleting your emulator and recreating it. Then if that doesn't work, I would backup any code you want to keep and start deleting your ide environment and android sdk and just start over.

Ive actually done that yesterday since something went wrong with the saving of my project so my project was deleted. Today I started over. Guess im going to have to start from fresh. Oh by the way, can you have a look over here and answer my question:
http://forum.xda-developers.com/showthread.php?t=2343814

actually I just checked the logcat and I do infact have 1 error. I attached the screenshot of it:

TwilightLoz said:
actually I just checked the logcat and I do infact have 1 error. I attached the screenshot of it:
Click to expand...
Click to collapse
This should not be an error of your app.

nikwen said:
This should not be an error of your app.
Click to expand...
Click to collapse
You mean that the error has nothing to do with my app? But now it wont let me run it since im getting that error!! I actually deleted EVERYTHING again and now im going to start fresh again (at least its good practise).
Could you give me the links to get the eclipese and the androis sdk/adt? Since ive downloaded all of them 3 times...

TwilightLoz said:
You mean that the error has nothing to do with my app? But now it wont let me run it since im getting that error!! I actually deleted EVERYTHING again and now im going to start fresh again (at least its good practise).
Could you give me the links to get the eclipese and the androis sdk/adt? Since ive downloaded all of them 3 times...
Click to expand...
Click to collapse
Of course, here you go: http://developer.android.com/sdk/installing/installing-adt.html
You say that it does not let you run the app. Can you install it? I guess that you cannot. Even if you could, there would be a bigger log output/stacktrace.
There should be errors shown in your IDE (Eclipse). Is there any red sign in your project code? (If there is one, there will be a red X in the Package Explorer view.)
I think that the problem is in your code.
Check this.

nikwen said:
Of course, here you go: http://developer.android.com/sdk/installing/installing-adt.html
You say that it does not let you run the app. Can you install it? I guess that you cannot. Even if you could, there would be a bigger log output/stacktrace.
There should be errors shown in your IDE (Eclipse). Is there any red sign in your project code? (If there is one, there will be a red X in the Package Explorer view.)
I think that the problem is in your code.
Check this.
Click to expand...
Click to collapse
I just deleted everything apart from my project before reading your reply...
I'll download it again and run my project again. I didnt get any red x by the way.

TwilightLoz said:
Basically I created a button on my app which links it to another java class. I already setted the layout for the java class using the setContentView method.
But whenenever I click on the button, it doesn't take me to that java class. Im still practising right now but ive gone through the whole project nd couldn't find whats going wrong. I literally cant find any errors.
This is what I did to link the button:
Code:
package com.tarikh.thebasics;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class splash extends Activity{
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button tut1 = (Button) findViewById(R.id.button1);
tut1.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.tarikh.thebasics.TUTORIALONE"));
}
});
}
as you can see, the tutorialone class has the following layout:
Code:
public class TUTORIALONE extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial1);
and the tutorial1.xml layout consists of a radiobutton (this is just rough). so whenever I click on the button, it should take me to the tutorialone class right?
Click to expand...
Click to collapse
First of all, I would make the Button variables as a "Field" Rather than a 1-time instance of your onCreate() method. A Field is a variable defined at the root of your Class. Example:
Code:
package com.tarikh.thebasics;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class splash extends Activity{
[COLOR="Lime"]Button tut1;[/COLOR]
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
[COLOR="lime"]tut1 [/COLOR]= (Button) findViewById(R.id.button1);
tut1.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
[COLOR="lime"] if (v.getId() == R.id.button1) {
startActivity(new Intent("com.tarikh.thebasics.TUTORIALONE"));
}[/COLOR]
}
});
}
The Lime-Green colored text is the only thing that needs to be change.
The 1st is now a Field, where that variable will be seen throughout the whole class, not just onCreate().
Then take away the Button declaration of tut1 in your onCreate() Method. this will make the tut1 Field (Button) = (your_id_here)
Edit: sorry, I misread. Disregard the "if " statement.
Cheers

1. Try it on a device if you can. I never use AVDs because I can run and debug an app about 8 times before my AVD even loads. Plus yours seems buggy.
2. Does it force close or just not work? if it FCs make sure you declared the second activity in your manifest.
3. Does the main xml button have an id?-- android:id="@+id/button1" ?
EDIT. Wait, your button should be in the activity_main.xml, not tutorialone. if its in tutorial one it weould try to reload that same activity.
actually it wouldnt even do anything probably, because your calling a button that isnt where you are.

Thanks for all your suggestions. I think I'm going to start fresh since Ive got more knowledge now. I'll take all your advices on board and if things go wrong, i'll post my problem here.

nikwen said:
Of course, here you go: http://developer.android.com/sdk/installing/installing-adt.html
You say that it does not let you run the app. Can you install it? I guess that you cannot. Even if you could, there would be a bigger log output/stacktrace.
There should be errors shown in your IDE (Eclipse). Is there any red sign in your project code? (If there is one, there will be a red X in the Package Explorer view.)
I think that the problem is in your code.
Check this.
Click to expand...
Click to collapse
Im going to download this as this has everything bundled together:
http://developer.android.com/sdk/index.html

Thanks guys for your co-operation, I just created the splash page and linked the button to the other layout. Got error but fixed them. It was good practice.
Didn't know running the app from your device instead of the emulator would be soo easy!! And not to mention less laggy.

TwilightLoz said:
Thanks guys for your co-operation, I just created the splash page and linked the button to the other layout. Got error but fixed them. It was good practice.
Didn't know running the app from your device instead of the emulator would be soo easy!! And not to mention less laggy.
Click to expand...
Click to collapse
Great.

Related

[Q] Calling new activity on a button click

Hey guys,
I'm new to android development and have been working through the Android Development guides on Google's site. I'm using what I've learned so far to create a simple app that enables the user to press a button and enter a second screen. I'm incredibly confused at this point and any help would be much appreciated. I have a class Project001.java with a button and would like class Project002.java to be launched when Button 1 is pressed. I have main.xml providing the layout for Project001 and main2.xml providing the layout for Project002. Here is what I have so far in Project001 (which I know is wrong).
package com.smith.Project001;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.smith.Project002;
public abstract class Project001 extends Activity implements OnClickListener {
Button button = (Button)findViewById(R.id.Button01);
abstract void setOnClickListener(View v);
// Implement the OnClickListener callback
public void onClick(View v) {
//do something when the button is clicked
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myIntent = new Intent();
myIntent.setClassName("com.smith.Project001", "com.smith.Project002");
startActivity(myIntent);
}}
I've been searching through the Google archives and can't seem to put all the pieces together. Thanks in advance for your help!
Try the tutorial here. The second one, called menus and intents, I think, shows starting one activity from another.
http://www.vogella.de/articles/Android/article.html
________________________________
Unrevoked forever
SkyRaider Sense 3.5
Radio 2.15.00.09.01
Try something like this in your main activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startNewActivityBtn = (Button) findViewById(R.id.newactivitybtn);
startNewActivityBtn.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
// put your intent and start activity here; should work fine
}
});
}
Click to expand...
Click to collapse
You really don't need abstract or implements. And there is no reason to import "Project2" into "Project1". Project2 should handle all that goes on in the new window. If you need to pass data to Project2 you can do that too
Thanks for the help so far guys,
I'm still having troubles with this code (new to development and very much appreciative of your help). I've done a lot of reading and I don't think I need to use intents because I have to data to pass from Project001 to Project002. All I need is to click the button and to move from Project001 to Project 002. My problem right now is that as soon as I run the app in the emulator, I get a force close. I've been trying to find a solution but haven't been able to. I've tried to implement the method you gave me and took the entire tutorial two posts up. Here is the new code. Again, any help is much appreciated.
package com.smith.Project001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Project001 extends Activity implements OnClickListener {
Button button = (Button)findViewById(R.id.Button01);
void setOnClickListener(View v) {
}
// Implement the OnClickListener callback
public void onClick(View v) {
setContentView(R.layout.main2);
//do something when the button is clicked
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startNewActivityBtn = (Button) findViewById(R.id.Button01);
startNewActivityBtn.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
// put your intent and start activity here; should work fine
}
});
}
Always look into logcat, it's REALLY helpful. Anyway, here's a couple of things I see wrong;
1) I'm not sure why you're having two layouts for one activity, just put them into one layout file
2) setContentView() needs to be in onCreate()
3) You can't call findViewById() before the layout file has been processed by setContentView()
Try this example. I think it does exactly what you want. It has two xml files (screen 1 and screen 2). When you press the button on the first screen, it displays the second screen.
http://www.warriorpoint.com/blog/2009/05/24/android-how-to-switch-between-activities/
________________________________
Unrevoked forever
SkyRaider Sense 3.5
Radio 2.15.00.09.01
Yep, that should work.
Please note that on the second Activity, a "Previous" or "Return" type button is not required; the hard Back Key on Android phones does the exact same thing as the code.

[Q] Playing new sound on each click

I've run into a little trouble and I'm wondering if someone can help me out.
I have a button with several sound effects that go with it. I'm wanting to play a different sound each time the button is pressed, but I just can't get things to work out. Can someone show me the way? Any help would be huge. This is the only thing keeping me from finishing. Here's a little code:
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.finn_whatthejugisthat);
mSoundManager.addSound(2, R.raw.finn_wordtoyourmother);
Button SoundButton = (Button)findViewById(R.id.Button1);
SoundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
mSoundManager.playSound(2);
}
});
}
}
If you want to play a different sound with each click, then you'll have to keep a global counter variable or global string that you change to the next audio file name with each click of the button--sort of a circular buffer. The code you have there tries to play both sounds on the same click and likely mixes them together at the same time if "playSound()" is asynchronous, but I don't know what the SoundManager class is so I have no idea.
Gene Poole said:
If you want to play a different sound with each click, then you'll have to keep a global counter variable or global string that you change to the next audio file name with each click of the button--sort of a circular buffer. The code you have there tries to play both sounds on the same click and likely mixes them together at the same time if "playSound()" is asynchronous, but I don't know what the SoundManager class is so I have no idea.
Click to expand...
Click to collapse
Okay, so I understand what you mean, but I don't know how to say that in Java. Could you give a short example? As for SoundManager, it's really a useless class I have that I was using to play my media. You can take a look here:
Code:
package com.andrew.finnandjake;
import java.util.HashMap;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager {
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
public SoundManager()
{
}
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1));
}
public void playSound(int index) {
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
public void playLoopedSound(int index) {
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
}
OK, I see it uses SoundPool. First, change your definition for addSound to:
Code:
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put([COLOR="Red"]Index[/COLOR], mSoundPool.load(mContext, SoundID, 1));
}
Here's code that should work to do a different tone each push and loop back to the beginning.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonSound extends Activity{
private SoundManager mSoundManager;
private int next=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager=new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(0,R.raw.freeze);
mSoundManager.addSound(1,R.raw.ascend);
mSoundManager.addSound(2,R.raw.bubble);
mSoundManager.addSound(3,R.raw.chiff);
Button SoundButton=(Button)findViewById(R.id.button1);
SoundButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
mSoundManager.playSound(next);
next++;
if(next>3)
next=0;
}
});
}
}
Gene Poole said:
OK, I see it uses SoundPool. First, change your definition for addSound to:
Code:
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put([COLOR="Red"]Index[/COLOR], mSoundPool.load(mContext, SoundID, 1));
}
Here's code that should work to do a different tone each push and loop back to the beginning.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonSound extends Activity{
private SoundManager mSoundManager;
private int next=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager=new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(0,R.raw.freeze);
mSoundManager.addSound(1,R.raw.ascend);
mSoundManager.addSound(2,R.raw.bubble);
mSoundManager.addSound(3,R.raw.chiff);
Button SoundButton=(Button)findViewById(R.id.button1);
SoundButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
mSoundManager.playSound(next);
next++;
if(next>3)
next=0;
}
});
}
}
Click to expand...
Click to collapse
Mkay, so I adjusted my code according to the example and everything came back error free; however, when I run the app and click the button, nothing happens. No sound, but no force close either.
I ran the Debugger and it's telling me that the SoundPool sample is not ready. "Sample 1 not READY", "Sample 2 not READY", etc.
I don't know. I assume you used different names for your sound files. I just grabbed those out of the "notifications" directory of my phone.
Gene Poole said:
I don't know. I assume you used different names for your sound files. I just grabbed those out of the "notifications" directory of my phone.
Click to expand...
Click to collapse
Alright, that's cool. Thanks a lot for all of the help. I owe you one.

[Q] Beginner seeking help - code issue?

Howdy all,
I'm very much a beginning and basically just toying around with different bits of code.
I've got the Home screen of my app with a button called About App. When I click on it, the app force closes.
If I remove the code between /** Back button **/ the app functions perfectly fine.
I'm assuming there is something I'm missing when I add that additional code.
Is someone able to assist with this? I'm sure it's something simple I'm missing but it's driving me nuts.
Code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class AboutApp extends Activity {
/** Grab aboutapp template **/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutapp);
/** Create the web view for htm file **/
WebView wv = (WebView)findViewById(R.id.aboutapp_webview);
wv.setWebViewClient(new WebViewClient() {
[user=439709]@override[/user]
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
wv.loadUrl("file:///android_asset/aboutapp.htm");
/** Back button **/
Button btn_ok = (Button) findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Main.class);
startActivityForResult(myIntent, 0);
}
});
/** Back button **/
}
}
I hate that. Looking at this for ages and only when I create a thread detailing my issue do I find the problem... I think.
The above code is looking for btn_ok. In the aboutapp.xml file, I've got android:id="@+id/ok_btn" - it should be btn_ok.
Will try this shortly and report back.
Confirmed - that was all it was.
hmmmmmm great you should keep in mind the name of your resources...so what you are exactly trying to make?
coolbud012 said:
hmmmmmm great you should keep in mind the name of your resources...so what you are exactly trying to make?
Click to expand...
Click to collapse
Not really making anything in particular at this stage. Just trying to understand it all - so I'm throwing together a whole lot of different things and trying stuff out.
I'm not a programmer - never have been. So I'm learning "everything" from scratch. It's going to be a long road a head. :good:
Yeah same here...I have already done java and now understanding the android programming (have already made some apps but for personal use only now going to make some professional apps and will host them on play store.)... If you want we both can work together...I mean as we both are freshers so we can help each other in different things...

[Q] how to change the starting activity

Hi there,
I would like some advice on what I should look for if I want to implement the following basic scenario:
the app starts with an activity (call it Activity_1) which contains a button
on clicking the button, takes me to a different activity (call it Activity_2)
next time i start the app, it takes me directly to Activity_2
and Activity_1 won't be seen again
So how can I change the startup activity?
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
thanks for the answer. i want to consider that the app is closed, like after restarting the device. i don't want it to be able to start with Activity_1 unless, let's say, i re-install the app.
i also had an idea about having a 3rd activity as the main one defined in the manifest, which on create changes to one of the other activities. but i don't know how that would be implemented. would it work?
octobclrnts said:
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
Click to expand...
Click to collapse
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
octobclrnts said:
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
Click to expand...
Click to collapse
K-RAD said:
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
Click to expand...
Click to collapse
That's absolutely right. You can store Strings and primitive values indexed by String keys.
octobclrnts said:
That's absolutely right. You can store Strings and primitive values indexed by String keys.
Click to expand...
Click to collapse
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Code:
package com.example.onetimeactivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
else
{
//do something else every other time
startActivity(new Intent(this,SecondActivity.class));
}
}
}
Code:
package com.example.onetimeactivity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class SecondActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
doLogon();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
edit.apply();
}
}
i managed to resolve it by adding android:noHistory="true" to the manifest. however, now i really can't see the first activity, not even if i rebuild the code ))
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
Thanks for catching my mistake. You're right that it does need an apply (or before API level 9, commit()) call.
If you don't want to see the activity MainActivity anymore, then you have to make some changes to your structure. You should make an Activity that will be the one that always shows when the user opens the app. That activity is the one who should check the SharedPreferences for your entry. If the entry does not exist, it should call the one-time-activity. Then the one-time-activity should do it's work and save the entry and call finish() to go back to the main activity (the one you usually want to be shown). This way the activity stack will be correct for the back key functionality.
what it sounds like you want is something like a splash/logon screen
like previously said use sharedprefs.
in the splash/logon call the sharedpref and make the default false (I use booleans, you can use ints or strings):
so it would be like this
Code:
SharedPreferences settings;
SharedPreferences.Editor editor;
boolean splash;
[user=439709]@override[/user]
public void onCreate() {
settings = getSharedPreferences("settings", 0);
splash = settings.getboolean("splash", false);
editor = settings.edit();
if(splash == false){
setContentView(//the view you are using);
//do everything else you need to do
button.setonclicklistener(new OnClickListener(){
editor.putboolean("splash", true);
editor.commit();
finish();
});
}else{
//open up your second activity
finish();
}
if its a login screen, when the user clicks logout you would do the editor and change "splash" to false.

Is my Dialogbox correct?

Hey guys, im on the process of building my app. Basically, so far, this is what should happen:
The user presses a button and a dialogbox appears. In the dialogbox, the user selects the days in which the reminder shall remind him. (If that makes sense...).
This is my Java code:
Code:
package yCM.medireminder;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ADD extends Activity implements OnClickListener{
private AlertDialog.Builder dialogBuilder;
private void days()
{
//Declaring the Variables
final ArrayList weekdays = new ArrayList();
dialogBuilder = new AlertDialog.Builder(this);
final String[] dayss = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
//Starting the Process
dialogBuilder.setTitle("Check the Days");
dialogBuilder.setMessage("Check the days when you will shall be reminded");
dialogBuilder.setMultiChoiceItems(dayss, null, new DialogInterface.OnMultiChoiceClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
weekdays.add(which);
}else if(weekdays.contains(which))
{
weekdays.remove(Integer.valueOf(which));
}
}
});
dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Your days have been set", Toast.LENGTH_LONG);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Your days have not been set", Toast.LENGTH_LONG);
}
});
// OUTPUT
AlertDialog dayDialog = dialogBuilder.create();
dayDialog.show();
}
Does everything look alright, the emulator isn't working for my and I have misplaced my phone (its on silent) so I have no way of checking whether it will work. I have linked the dialog box to a button so Im sure that when the button is clicked, the dialog box should appear.
It is recommended to use DialogFragments instead of simple dialogs. That way the system would orientation changes etc. for you.
However, you would need to convert your Activity into a FragmentActivity.
nikwen said:
It is recommended to use DialogFragments instead of simple dialogs. That way the system would orientation changes etc. for you.
However, you would need to convert your Activity into a FragmentActivity.
Click to expand...
Click to collapse
I do plan on making the app on permenantly on portrait mode so I don't think the orientation would be any problem even when the user switches to landscape.
Why would I need to convert my activity to fragmentactivity? What does this do? Also my min sdk is set to api level 8 (2.2 i believe).
Other than that, does the code seem alright?
TwilightLoz said:
I do plan on making the app on permenantly on portrait mode so I don't think the orientation would be any problem even when the user switches to landscape.
Why would I need to convert my activity to fragmentactivity? What does this do? Also my min sdk is set to api level 8 (2.2 i believe).
Other than that, does the code seem alright?
Click to expand...
Click to collapse
You just need to do this if you want to use the DialogFragment. For the normal dialog you don't need it.
You can use fragments on Android 1.6+ if you include the supportv4 library.
Try it. That's all I can say. There might be other things that make it crash, apart from that code. Maybe related to the Android lifecycle.
thanks for the info. Just runned it, everythings working smooth for now. Any idea on how to make the android system recognise/link the days of the week on my string? I did have a read through this but didn't quite understand it. I have a feeling that I should be using something got to do with the calender though...
http://developer.android.com/reference/java/util/Date.html#getDay()
TwilightLoz said:
thanks for the info. Just runned it, everythings working smooth for now. Any idea on how to make the android system recognise/link the days of the week on my string? I did have a read through this but didn't quite understand it. I have a feeling that I should be using something got to do with the calender though...
http://developer.android.com/reference/java/util/Date.html#getDay()
Click to expand...
Click to collapse
You can get the current time using
Code:
System.currentTimeMillis()
Then create a Date from it:
Code:
Date myDate = new Date(System.currentTimeMillis();
Then you can format it using the SimpleDateFormat class: http://developer.android.com/reference/java/text/SimpleDateFormat.html
For some things the Calendar class might be better: http://developer.android.com/reference/java/util/Calendar.html
However, I have not worked with it yet.

Categories

Resources