Junior — Middle
What methods ensure data state preservation when recreating an Activity in Android?
sobes.tech AI
Answer from AI
To preserve data state when recreating an Activity in Android, the common approach is to use save and restore state methods via Bundle.
Main approaches:
- Override the
onSaveInstanceState(Bundle outState)method and save necessary data intooutState. - In the
onCreate(Bundle savedInstanceState)oronRestoreInstanceState(Bundle savedInstanceState)method, restore data fromsavedInstanceState.
Example:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("key", someValue);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
someValue = savedInstanceState.getString("key");
}
}
You can also use ViewModel to store data that survives Activity recreation without the need for manual saving in a Bundle.