Android onSaveInstanceState | How to save an Android Activity state using save instance state?

Published by inkskull on

Checkout Android onSaveInstanceState | How to save an Android Activity state using save instance state?

You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter.

@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("boolean", true);
  savedInstanceState.putDouble("double", 2.2);
  savedInstanceState.putInt("int", 1);
  savedInstanceState.putString("string", "Welcome Android");
}

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

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com