2 minutes

How to Save Android Application’s Activity State

By Editorial @stacktips, On Sep 17, 2023 Android 2.34K Views

The Activity class provides two methods onSaveInstanceState() and onRestoreInstanceState(), for saving and restoring activity state. The onSaveInstanceState( ) method is a callback method that is used to save the application state.

public void onSaveInstanceState(Bundle savedInstanceState) {
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is killed and restarted.
  savedInstanceState.putBoolean("key1", true);
  savedInstanceState.putDouble("key2", 1.9);
  savedInstanceState.putInt("key3", 1);
  savedInstanceState.putString("key4", "Welcome back to Android");

The Bundle is essentially a way of storing a Key value map. And it will get passed in to onCreate() and also onRestoreInstanceState() where you can extract the values as follows.

public void onRestoreInstanceState(Bundle savedInstanceState) {
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("key1");
  double myDouble = savedInstanceState.getDouble("key2");
  int myInt = savedInstanceState.getInt("key3");
  String myString = savedInstanceState.getString("key4");
stacktips avtar


StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.