How does System retains ListView scroll posion automatically?
You may have noticed that some data does not get affected during rotation even if you have not handled it onSaveInstanceState
method. For example
- Scrollposition Text in EditText
- Text in EditText etc.
What happens when the screen rotates?
When the screen rotates System kills the instance of the activity and recreates a new instance. System does so that most suitable resource is provided to activity for different configuration. Same thing happens when a full activity goes in multipane Screen.
How does system recreates a new Instance?
System creates a new instance using old state of the Activity instance called as "instance state". Instance State is a collection of key-value pair stored in Bundle
Object.
By default System saves the View objects in the Bundle for example.
eg Scroll position EditText etc.
So if you want to save additional data which should survive orientation change you should override onSaveInstanceState(Bundle saveInstanceState)
method.
Be careful while overriding onSaveInstance method!!!
@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);
}
Always call the super.onSaveInstanceState(savedInstanceState)
ekse the default behavior will not work. ie EditText value will not persist during orientation. Dont beleive me ? Go and check this code.
Which method to use while restoring data?
onCreate(Bundle savedInstanceState)
OR
onRestoreInstanceState(Bundle savedInstanceState)
Both methods get 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.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
mTextView.setText(savedText);
}
}
OR
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
Always call super.onRestoreInstanceState(savedInstanceState)
so that
System restore the View hierarchy by default.