I have four activity for my application, Main Activity -> second Activity-> Third Activity -> Fourth Activity. Each Activity contains the onBackPressed method implemented. Every time when the onBackPressed method called, it sends an intent to the previous activity. For Example, in Fourth Activity onBackPressed method, it contains an intent to go to the previous Activity, which is the Third Activity. This works fine upto the MainActivity. When I press on the back button on the MainActivity it must exit the application. However, it just starts the next activity, which is the second Activity. What causes this bug???
Here is some relevant code.
From the fourth activity:
#Override
public void onBackPressed() {
Intent intent = new Intent(this,third.class);
intent.putExtra("id",FinalID);
intent.putExtra("Image Item", categoryItem);
startActivity(intent);
}
From the third activity:
#Override
public void onBackPressed() {
Intent intent2 = new Intent(this, second.class);
intent2.putExtra("Image Item", categoryItem);
Toast.makeText(this, "theFinalActivity=" + categoryItem.getId(), Toast.LENGTH_SHORT).show();
startActivity(intent2);
}
The second activity looks like the following.
#Override
public void onBackPressed() {
next = false;
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
And finally the code in the MainActivity:
#Override
public void onBackPressed() {
System.exit(0);
}
Android System internally handles the backstack for the activities. You don't need to explicitly handle going back if you're not supposed to override the default behavior. In your case, On pressing back, you're not popping the current activity, instead you're pushing a new one into the backstack. This will result in ambiguous behavior of your back button.
First, the onBackPressed function is not required to be implemented only if you are caring about taking care of the activity stack (i.e. finishing up your third activity will bring back the second and finishing the second activity will bring up the first one and so on). The activity stack is already taking care of it.
Secondly, if you want to pass the data to a caller activity from the activity that you have opened from the caller, this is not the ideal way to do so. I would like to recommend you to read this documentation where it explains how to pass such intents in a graceful manner using the life-cycle functions provided by Android.
Just to give you a heads up, here are three steps for you to pass the data between activities in a backward direction.
You need to start the second activity from the first activity using startActivityForResult instead of startActivity with a request code passed along with it (so that you can differentiate between different request codes from other activity if there is any).
Then in your second activity, if you need to pass something to your caller activity (i.e. the first activity), you need to use setResult to pass the desired data back to the caller and finish() the second activity.
In the first activity, you need to implement onActivityResult function to get the data back from the second activity.
Here is a nice example of the overall implementation where you can take a look too.
I know that you are expecting that the system.exit(0) should kill the application whatever the situation is. However, in Android, it does not work in the way that you have expected I think. I am quoting from this answer on StackOverflow to explain how the system.exit(0) works.
System.exit(0) - Restarts the app with one fewer activity on the
stack. So, if you called ActivityB from ActivityA, and System.exit(0)
is called in ActivityB, then the application will be killed and
started immediately with only one activity ActivityA.
I hope that helps!
Related
i working on an android application, i have an api object that initialised to null in the main activity, i initilise it in another activity, and when i finish i call back my main activity like this:
startActivity(new Intent(this, MainActivity.class));
when i come back to the main activity, it set up my api object to null;
i don't know how i do to keep my api object set up, when i come back to the main
i tried use static and protected but it's still not work
Would someone have a solution to avoid this problem?
your mistake is that you start MainActivity again, you can just finish second activity.
if you want to send data from second activity to MainActivity you can use onActivityResult method
check this to read more link
I have multiple activities. In my main activity, I have my listview within an arraylist. When I go to the second activity and press the back button on the second activity to return my main activity, my arraylist size becomes zero therefore I am losing my listview entries.
Is there any way to keep my arraylist when I go back to the previous activity?
Note: On the second activity, my code is as follows:
public void onBackPressed(){
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivityForResult(intent, 0);
}
Given the comments you have left I'd suggest you create a management class. This class will store all of your default values and you can update it as needed from other classes.
You don't need to override onBackPressed() because the default behavior has your list retained. By overriding onBackPressed(), you are recreating MainActivity which consumes more resources as you are having two MainActivity opened (the initial in the background and the latter activated by onBackPressed ())
I have two Activities in one application.
First one updates its TextViews every 3 seconds. It works fine.
When the keyguard (lock screen) is activated the first activity launches the second activity which appears over the lock screen (in order to show data even if the screen is locked). It also works fine.
I would like the TextViews of the second activity to be updated periodically by the first activity. I have played hours with this and tried a lot of suggestions I found with Google but none of them worked for me. The second activity always crashes with NullPointerException at the moment when the TextView.setText() is called.
What is the best practice for doing this?
Thanks in advance for any help.
I don't think there is a good way to do this, as your first activity could get collected by the system, and you generally don't want to do work after onPause has been called.
I would move that logic that updates the views into a service that runs in the background. Since it sounds like you only need this service while the application is running I would create a bound one.
http://developer.android.com/guide/components/services.html
You can pass the data on calling another activity as :
Intent intent =new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringExtra("TextName","Value");
startActivity(intent);
As Ashish said you could use EventBus.
Add the library to your app and in your Second Activity register your activity in the EventBus in onCreate method:
EventBus.getDefault().register(this);
Create a new class in your project to define an event type:
public class TestEvent {
public TestEvent() {}
}
So in your second activity create a method to receive the event:
public void onEvent(TestEvent event) {
//stuff to do
}
Now, in your first activity you just have to "fire" the event in the method executed each 2 seconds:
EventBus.getDefault().post(new TestEvent());
Each time you execute post method, the onEvent of your second activity will be run.
A way to do it is by defining a Singleton object that holds the value to be displayed on the TextView, for instance, a Integer or a String.
Both activities have access to read/write into this object. So when you come back to the second activity, maybe on the onResume() method..you can the following:
public void onResume() {
super.onResume();
textview.setText(""+ MySingleton.getInstance().getValue());
}
On the other activity:
public void updateMethod() {
int newValue = .....;
MySingleton.getInstance().setValue(newValue);
}
This will make sure that whenever you come back to this activity (as onResume() is called), the value will be updated into the TextView. Of course, assuming that you are updating the value from the other activity accordingly.
Note this is the simplest solution you can do, professionally, I would do an event driven solution, where the observer gets notified when the value is changed. For that you can play with http://square.github.io/otto/ library.
I have a problem with a nullpointer exception when I return to a previous activity by using the UP button in the action bar.
I'll try to explain my flow:
ActivityA.java:
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra(KEY, value);
startActivity(intent);
ActivityB.java:
Obj o = getIntent().getSerializableExtra(ActivityA.KEY);
o.doStuff();
Intent intent = new Intent(this, ActivityC.class);
startActivity(intent);
ActivityC.java:
// Do some stuff, then finish
finish();
Now all this works fine when I press a button on Activity C that triggers the finish()part.
The problem occurs when instead of pressing that button I press the UP button on the action bar to go back to Activity B. Then I get a nullpointer because he tries to recreate Activity B, and fails on the line o.doStuff();
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{ActivityB}:
java.lang.NullPointerException
How can I solve this? How can I prevent the Activity B from needlessly recreating? Please keep in mind that I'm doing this Android stuff since Tuesday ..
I know that this might not be what you want but this scenario is not uncommon and what I find myself doing at times is if (o == null) in ActivityB I do finish(). This leads the user back to ActivityA. If ActivityA is not in the backstack, then the app finishes. This is what happens with Instagram at times. It's not perfect but it's not that annoying, I think.
If it's a must to go back to B, you could actually just transfer your Object in your intent to C. And before finish() in C, you could fire a new StartActivity(B.class) with Object as extras to B.
You should look at the Android Activity lifecycle. The problem is that starting a new Activity can destroy an old one in memory, and if you don't return to an Activity for a while its memory will be reclaimed. You need to take a look at onPause() and onResume() to see what you can do to save state.
https://developer.android.com/training/basics/activity-lifecycle/starting.html
It's not that Android "needlessly" recreates the Activity, it does it all the time. If you change orientation, your Activity is destroyed and recreated. If you start a bunch of apps and Android needs the memory currently held by an inactive app, it'll be destroyed and will be recreated when you next launch it.
As an aside, if you're not going to use the lifecycle callbacks onPause() and onResume(), you should at least check to see if your object is null and recreate it in onCreate().
I'm new to Android programming, so I'm probably missing something trivial here.
The goal is to create a prototype of a digital signage app. Right now I've created three activities; MainActivity has a method which switches to the second activity after a certain period of time. The same method is then called from the second activity to third, and from third back to main.
There are two problems though: first, is it ok to create new Intent every time the app switches between the activities? As I mentioned, I started learning Android recently, so please don't be mad if this is a super dumb question.
Second: the app launches itself after I've hit home button in my emulator even though I'm calling finish(); after the startActivity(intent);
Here is the method in the MainActivity:
public void switchActivities(final Class<?> classObject) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), classObject);
startActivity(intent);
finish();
}
}, 1000);
}
The activities Second and Third extend MainActivity and call the switchActivities method:
switchActivities(Third.class); (from Second to Third).
Thanks in advance!
UPDATED:
I added public boolean isRunning = true; to my MainActivity and
if(isRunning) startActivity(intent); to the switchActivities method;
I also added a method
#Override
protected void onPause(){
super.onPause();
isRunning = false;
}
as advised here.
Although finish(); should have cleared the method stack, the app didn't close after pressing Home button but went to previous activity instead, so I added this line to every activity in the AndroidManifest file:
android:noHistory="true"
as advised here.
Sorry for not upvoting helpful answers, I don't have enough reputation yet.
Yeah, it is the proper way of switching activities by creating new intents. I am little confused about your second questions. if you are saying that as you are using postDelayed method which gets triggered after some interval, is being called even you have finished your activity or pressed home button, you can handle this by creating a boolean variable isRunning in your activity which gets false when onPause or onDestroy gets called. Then you in your postdelayed method, you can check the flag and then proceed as required.
The Intent used in navigation between the Activities , so it's cool to using it , no problem
The second problem because the Activity object still in your memory after you hit Home button , then the Handler will continue its work and start the activity after the certain period you determined in your code
For your first question: it's not a problem that you're creating a new Intent every time
The second one is a bit trickier. When you press the home button the current activity stays in memory, so it can start the new one even though you think it's not running. The easiest way to handle this to check weather the activity is finishing, and if so, you don't show the next one.
if (!isFinishing()) startActivity(intent);
This if statement prevents your activity to start a new one when it's in the background.