May 01, 2019

How to save an Android Activity state using save instance state

      On this blog am going to explain how to save activity state when the activity is destroyed, I have been working on the android SDK platform, and it is a little unclear how to save an application's state.

You're explicitly destroying your activity such as by pressing back. Actually, the scenario in which this savedInstanceState is used, is when Android destroys your activity for recreation. For example, If you change the language of your phone while the activity was running (and so different resources from your project need to be loaded). Another very common scenario is when you rotate your phone to the side so that the activity is recreated and displayed in landscape. You can use this technique to store instance values for your application (selections, unsaved text, etc.).

To overcome this issue you need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter, This bundle will be passed to onCreate if the process is killed and restarted.

public void onSaveInstanceState(Bundle savedInstanceState) {
  savedInstanceState.putBoolean("KeyBoolean", true);
  savedInstanceState.putDouble("KeyDouble", 1.9);
  savedInstanceState.putInt("KeyInt", 1);
  savedInstanceState.putString("KeyString", "Welcome back to Android");

The Bundle is essentially a way of storing the values as  Name-Value Pair, and it will get passed in to onCreate() and also  onRestoreInstanceState(Bundle savedInstanceState) where you would then extract the values like this,

public void onRestoreInstanceState(Bundle savedInstanceState) {
  boolean myBoolean = savedInstanceState.getBoolean("KeyBoolean");
  double myDouble = savedInstanceState.getDouble("KeyDouble");
  int myInt = savedInstanceState.getInt("KeyInt");
  String myString = savedInstanceState.getString("KeyString");