What to save and what not to?
Ever wondered why the text in the EditText
gets saved automatically while an orientation change? Well, this answer is for you.
When an instance of an Activity gets destroyed and the System recreates a new instance (for example, configuration change). It tries to recreate it using a set of saved data of old Activity State (instance state).
Instance state is a collection of key-value pairs stored in a Bundle
object.
By default System saves the View objects in the Bundle for example.
- Text in
EditText
- Scroll position in a
ListView
, etc.
If you need another variable to be saved as a part of instance state you should OVERRIDE onSavedInstanceState(Bundle savedinstaneState)
method.
For example, int currentScore
in a GameActivity
More detail about the onSavedInstanceState(Bundle savedinstaneState) while saving data
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
So by mistake if you forget to call
super.onSaveInstanceState(savedInstanceState);
the default behavior
will not work ie Text in EditText will not save.
Which to choose for restoring Activity state?
onCreate(Bundle savedInstanceState)
OR
onRestoreInstanceState(Bundle savedInstanceState)
Both methods get the same Bundle object, so it does not really matter where you write your restoring logic. The only difference is that in onCreate(Bundle savedInstanceState)
method you will have to give a null check while it is not needed in the latter case. Other answers have already code snippets. You can refer them.
More detail about the onRestoreInstanceState(Bundle savedinstaneState)
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from the saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
Always call super.onRestoreInstanceState(savedInstanceState);
so that System restore the View hierarchy by default
Bonus
The onSaveInstanceState(Bundle savedInstanceState)
is invoked by the system only when the user intends to come back to the Activity. For example, you are using App X and suddenly you get a call. You move to the caller app and come back to the app X. In this case the onSaveInstanceState(Bundle savedInstanceState)
method will be invoked.
But consider this if a user presses the back button. It is assumed that the user does not intend to come back to the Activity, hence in this case onSaveInstanceState(Bundle savedInstanceState)
will not be invoked by the system.
Point being you should consider all the scenarios while saving data.
Relevant links:
Demo on default behavior
Android Official Documentation.