DEV Community

Cover image for How to Save an Android Activity State Using Save Instance State?
amy acker
amy acker

Posted on

How to Save an Android Activity State Using Save Instance State?

Saving and restoring an activity UI state is an important part of user experience. In such cases, the client expects the UI state to continue as before, however, the framework demolishes the action and any state present in it. You may have seen during testing that screen-rotation resets all information gathered from the client. Same is the case when a user presses the back button by mistake. Screen rotation is one of the numerous life-cycle changes in Android that can destroy and reset the Activity and cause all information to be lost. Definitely not an extraordinary user experience!

In order to Save and Restore UI state, I override two most common methods for this purpose:

Alt Text

onSaveInstanceState():

In order to save sates of UI, I override onSaveInstanceState(Bundle savedInstanceState) and save all the data of the UI in savedInstanceState Bundle.

This method is called before onStop() in older versions of Android (till android 8.0) and can be called after onStop() for newer versions.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("StringKeyForBoolean", false);
savedInstanceState.putDouble("StringKeyForDouble", 3.4);
savedInstanceState.putInt("StringKeyForInteger", 5);
savedInstanceState.putString("StringKey", "Folio3/blog");
// etc.
}

The Bundle is essentially a way of storing an NVP ("Name-Value Pair") map, and it will get passed into onRestoreInstanceState() where you would then extract the values like this:

Alt Text

This method is called after onStart().

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Restore UI state using savedInstanceState.

Var1 = savedInstanceState.getBoolean("StringKeyForBoolean", false);
Var2 = savedInstanceState.getDouble("StringKeyForDouble");
Var3 = savedInstanceState.getInt("StringKeyForInteger");
Var4 = savedInstanceState.getString("StringKey");

}

Using this way you can save all the states and other data variables that could be lost on screen rotation or when the current activity goes into the background. Saving and restoring states of UI is a good practice in android app development.
Note: When an activity is created for the first time there will be no data in the save instance state bundle.

Check out this guide if you are planning to launch an app.

Top comments (0)