The 29th Saltshaker The 29th Saltshaker - 1 year ago 59
Android Question

How come sometimes when I press back button, there are more Activities than there should be?

I don't know how to phrase this question.

My app has a simple ViewPager and you click on something in one of those page Fragments and it takes you to another Activity. Press the back button and it takes you back to the ViewPager. Press back again and it closes the app.

However, sometimes when I press the back key at the ViewPager, it takes me back to the other Activity again, and then I press back and it takes me to the ViewPager, and so on, until the app finally closes. In other words it's like there are spare, leftover instances of either the ViewPager or the other Activity in the backstack (I think it's called), but I have no idea how or why this is happening.

I also don't know how to reproduce the error, which is even more frustrating. Most of the time it works as expected, but sometimes the leftover instances just show up out of nowhere as I am pressing back.

How can I guarantee better that when I press the back button on the other Activity, it goes back to the ViewPager, and when I press back on the ViewPager, it closes the app?

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case //called when I press back button on the phone or the back-arrow on the toolbar
return true;
return super.onOptionsItemSelected(item);

//and then usually that's all I have, but in one particular Activity, I do override the function:

public void onBackPressed() {
if (some conditions are met) {
else {
//display some error message

Here is how I launch my Activities:

public void launchSomeActivity() {
Intent intent = new Intent(getActivity(), ActivityName.class);
intent.putExtra( etc etc etc );
startActivityForResult(intent, REQUEST_CODE);

Answer Source

Likely you are seeing a nasty long-standing Android bug. If you launch your app for the first time from an IDE, or from the installer, when you put the app in the background and launch it again from the HOME screen, Android creates another instance of your root Activity. This would exhibit exactly the behaviour you are reporting. If you launch the app for the first time by pressing the app icon from the HOME screen (or list of available apps), the problem does not occur.

See Re-launch of Activity on Home button, but...only the first time

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download