18

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?

Andres
  • 6,080
  • 13
  • 60
  • 110

2 Answers2

31

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 :)

Zhenghong Wang
  • 2,117
  • 17
  • 19
  • Worked great! To save the data I used `getIntent().putExtras()` because `getIntent().getExtras()` is null at that time where you didn't save anything yet. – Andres Oct 11 '13 at 16:35
  • 1
    Can you share an example? I'm trying to implement this in onStop/onResume, but not having much luck. – snapplex May 21 '15 at 16:22
  • 3
    It's incredible how Android Developers recommend us to use `onSaveInstanceState`, `onRestoreInstanceState` and `onCreate` but it is very unstable. Thanks for sharing this, it solved my problem – Renan Bandeira Jul 06 '16 at 12:58
  • 2
    Just get null when call `getIntent().getExtras()` in `onResume()`. More detail, please? – Jacky Feb 12 '19 at 04:00
  • What happens if the user goes through multiple other activities and eventually comes back to the original activity? intents when they come back might be overridden. – rj2700 Apr 05 '19 at 15:12
  • wouldn't onPause() be better paired with onResume(), or onStop() + onStart()? – Literate Corvette Sep 15 '22 at 22:13
-3

You can save all the stuff from SavedInstance in the bundle or variable.

And set the data on onActivityCreated method like :

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        // Do your stuff here

}
SweetWisher ツ
  • 7,296
  • 2
  • 30
  • 74