-1

I have three activities Main, Item, and ItemDetail

Item has Main set to Parent in manifest

<activity 
  android:name=".Activities.Item"
  android:parentActivityName=".Activities.Main"
/>

ItemDetail has Item set to Parent in manifest

<activity 
  android:name=".Activities.ItemDetail"
  android:parentActivityName=".Activities.Item"
/>

Here is what the activity flow should look like visually

Main > Item > ItemDetail 

Both Item and ItemDetail extend from BaseActivity

public class Item extends BaseActivity { ... }
public class ItemDetail extends BaseActivity { ... }

BaseActivity displays and enables home button

 getSupportActionBar().setHomeButtonEnabled(true);
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now here is the problem: when pressing BACK button from ItemDetail activity, Item is brought to the foreground which is the expected behavior, right? However, when HOME button is pressed from ItemDetail activity, Item activity's onDestroy and onCreate are called, indicating (obviously) that Item activity is being destroyed before being recreated.

My question is why is Item activity destroyed and when pressing home button from ItemDetail but not back button. This makes no sense to me.

TL;DR

My app is crashing when pressing home because I expected Item to remain on the activity stack and maintain state, but activity is unexpectedly destroyed resulting in a null pointer error.

edit

Yes, I have onSavedInstance state implemented and working, it's just that the saved states is gone, calling this line from Item activity's onCreate returns true

null == savedInstanceState; // returns true
the_prole
  • 8,275
  • 16
  • 78
  • 163
  • It makes pretty much sens as non foreground Activity may be destroyed at any time – Selvin Aug 21 '17 at 21:35
  • Possible duplicate of [Acivity is getting destroyed while pressing the home button.](https://stackoverflow.com/questions/14314252/acivity-is-getting-destroyed-while-pressing-the-home-button) – Khaled Qasem Oct 19 '17 at 11:53

1 Answers1

2

You shouldn't assume any activity remains on the backstack and maintains state. Instead you should implement onSaveInstanceState and onRestoreInstanceState properly. The framework may kill your Activity at any time it isn't foreground. There's even a developer option setting to help test this, which will close all activities as soon as they're no longer foreground. I suggest testing your app with this mode every so often.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • I should have mentioned that. I do have onSavedInstance state implemented and working. Configuration changes like screen re-orientation are handle properly when `onDestroy` and `onCreate` are called. It's just there is no saved instance states available when pressing the back button from `ItemDetail` i.e. `null == savedInstanceState` returns true. – the_prole Aug 21 '17 at 21:55