savedInstanceState
is a method parameter onCreate() which receives an argument of the type Bundle.
It is used by the system to, when recreating an Activity, allow restore state it had at the time it was destroyed, for example, due to the user running the device.
It is understood that the status here only refers to the contents of the views of the layout of Activity, that is, the system only automatically saves the status of the layout.
Any other type of information that Activity has will be lost unless explicitly stored in this Bundle.
For this purpose Activity makes available the method onSaveInstanceState() which is called before the Activity can be destroyed. The system passes to it the Bundle object which is later recovered in the method onCreate()
when the Activity is recreated, allowing it to be saved and then retrieved other type of information.
Example of documentation where the value of the variables is stored mCurrentScore
and mCurrentLevel
:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
which are then recovered in the onCreate()
, if the Activity has been recreated:
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
In the code example that put the question savedInstanceState
is only being used to verify that the onCreate()
is being called due to a recreation of Activity or not.
If savedInstanceState == null
is because Activity is being created for the first time, in which case the Placeholderfragment and placed in the R.id.container
.
Direct from the source is the explanation https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
– Ismael
My English is shit...?
– Aline
The answer has already been given, but I add that it is for when you turn the screen... You know? At that point, the entire Activity is destroyed and rebuilt from scratch. Then, when someone rotates the screen, you program to save the data that is on that screen and then put it back on the screen, now in another orientation (Landscape or Portrait)
– Mr_Anderson