Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 819
Andres Avatar asked Oct 11 '13 03:10

Andres


People also ask

When in the activity lifecycle is onSaveInstanceState () called?

Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.

When onResume () method is called?

onResume() is called at the start of the active lifetime; more specifically, it is called at the start of the active lifetime; more specifically it is called after onRestoreInstanceState(Bundle), onRestart(), or onPause() for your activity to start interacting with the user.

What is onResume ()?

4. onResume() is called whenever you navigate back to the activity from a call or something else. You can override the onResume method similarly as onCreate() and perform the task.

How do I use onSaveInstanceState and onRestoreInstanceState on Android?

The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.


1 Answers

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

like image 157
Zhenghong Wang Avatar answered Nov 06 '22 04:11

Zhenghong Wang