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?
Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With