How to retrieve onSaveInstanceState() bundle in onResume()?

Andres picture Andres · Oct 11, 2013 · Viewed 17.7k times · Source

I am having a problem related to saving my Activity state. I searched and read about lots of questions here in SO but I couldn't get an answer for my question.

I have an Activity A with 2 Fragments. The Activity A holds the data which is showed by the Fragments. When I launch a new Intent for my settings Activity the Activity A is paused (not destroyed), onPause() and onSaveInstanceState() methods are called, so I save all my data in onSaveInstaceState().

When I return from my settings using back button Activity A is displayed again but onCreate() method is not being called because the Activity was not destroyed, instead onResume() method is called but I lost the state of my variables in Activity A and I can't access the Bundle I saved in onSaveInstanceState() because onCreate() is not called.

So onSaveInstanceState() is only useful when you rotate the screen? How can I access all the data I saved in onSaveInstanceState()? Or I should save them to a file or SharedPrefs to access them in onResume() later?

Answer

Zhenghong Wang picture Zhenghong Wang · Oct 11, 2013

Can this help?
1. Use getIntent().putExtras() in onStop() to save your data into Activity's bundle.
2. Then getIntent().getExtras() in onResume() to retrieve it.

And you should do a null check before access the bundle :)