I\'m trying to save and restore the state of an Activity
using the methods onSaveInstanceState()
and onRestoreInstanceState()
.
The state you save at onSaveInstanceState()
is later available at onCreate()
method invocation. So use onCreate
(and its Bundle
parameter) to restore state of your activity.
I just ran into this and was noticing that the documentation had my answer:
"This function will never be called with a null state."
https://developer.android.com/reference/android/view/View.html#onRestoreInstanceState(android.os.Parcelable)
In my case, I was wondering why the onRestoreInstanceState wasn't being called on initial instantiation. This also means that if you don't store anything, it'll not be called when you go to reconstruct your view.
I found that onSaveInstanceState is always called when another Activity comes to the foreground. And so is onStop.
However, onRestoreInstanceState was called only when onCreate and onStart were also called. And, onCreate and onStart were NOT always called.
So it seems like Android doesn't always delete the state information even if the Activity moves to the background. However, it calls the lifecycle methods to save state just to be safe. Thus, if the state is not deleted, then Android doesn't call the lifecycle methods to restore state as they are not needed.
Figure 2 describes this.
I think this thread was quite old. I just mention another case, that onSaveInstanceState()
will also be called, is when you call Activity.moveTaskToBack(boolean nonRootActivity)
.
The main thing is that if you don't store in onSaveInstanceState()
then onRestoreInstanceState()
will not be called. This is the main difference between restoreInstanceState()
and onCreate()
. Make sure you really store something. Most likely this is your problem.
It is not necessary that onRestoreInstanceState will always be called after onSaveInstanceState.
Note that : onRestoreInstanceState will always be called, when activity is rotated (when orientation is not handled) or open your activity and then open other apps so that your activity instance is cleared from memory by OS.