top of page
  • Writer's pictureMeghan Gill

Saving and Retrieving Instance State in Android Activities

Updated: Aug 5, 2021


Saving Instance State

In an activity or fragment we can use a bundle to store the state of our activity. The method onSaveInstanceState() provides us a bundle for that purpose.


onSaveInstanceState() isn’t necessarily a lifecycle method but it provides us a bundle where we can store the instance state. A bundle is a way to pass data between activities using key/value pairs.


What's an Instance State?

Each time we open an android app that isn’t already running we get a new instance. We want to save changes a user has made while using the app in case of configuration changes or lifecycle changes. For example if a user rotates the phone or an app goes into the background, we don't want a user to lose their progress.



To save information to the bundle you can use different methods such as putInt( ) or putString( ). As parameters it takes a key value pair. The key should be a final static variable.


@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString(KEY_FACT, mFact);
    outState.putInt(KEY_COLOR, mColor);
}

Add class member variables so that the key variables are public static final. Make sure the variables have a default value. Update their usage in code.


public static final String KEY_FACT = "KEY_FACT";
public static final String KEY_COLOR = "KEY_COLOR";
private String mFact = FactBook.facts[0];
private int mColor = Color.parseColor(ColorWheel.colors[8]);


Retrieving Instance State

We can retrieve the saved instance state by using the bundle or the method restoreInstanceState( ). The difference is that if you use the bundle from onCreate you have to make sure it isn’t null.


We need to populate our fields then update our views to show the values.



@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    mFact = savedInstanceState.getString(KEY_FACT);
    factTextView.setText(mFact);

    mColor = savedInstanceState.getInt(KEY_COLOR);
    relativeLayout.setBackgroundColor(mColor);
    showFactButton.setTextColor(mColor);

}

The instance is now saved.



874 views0 comments

Recent Posts

See All
bottom of page