Sobes.tech
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 into outState.
  • In the onCreate(Bundle savedInstanceState) or onRestoreInstanceState(Bundle savedInstanceState) method, restore data from savedInstanceState.

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.