Sobes.tech
Junior — Middle

What methods can be used to retain and restore the state of an Activity in Android?

sobes.tech AI

Answer from AI

In Android, the following methods are used to retain and restore the Activity state:

  • onSaveInstanceState(Bundle outState) — called before the Activity is destroyed, where you can save the state (e.g., form field values) into a Bundle object.

  • onRestoreInstanceState(Bundle savedInstanceState) or receiving the Bundle in onCreate(Bundle savedInstanceState) — where the saved data is restored.

  • ViewModel — an architecture component that preserves data during configuration changes (e.g., screen rotation) and is independent of the Activity lifecycle.

  • Saving data to persistent storage (SharedPreferences, database) — for longer-term storage.

Example of saving state:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("key", editText.getText().toString());
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        String text = savedInstanceState.getString("key");
        editText.setText(text);
    }
}
What methods can be used to retain and restore the… - sobes.tech