Save and restore activity data in Android

In Android, an activity represents a screen that you see on an android device. The activity can be destroyed by the android system when you press the back button or home button or when you rotate the screen from portrait to landscape. Before the activity is destroyed, you might want to save some data so when you still have the same data when you navigate back to the activity, or rotate the screen back from landscape to portrait.

To save the data before the activity is destroyed. You can do it in the onSaveInstanceState(Bundle savedInstanceState) method. The data is saved in name value pair format. In this example, the names are my_string, my_boolean, my_double, my_int and my_parcelable. For primitive type of data, you can put the value directly or in a variable. For complex data object, you need to implement Parcelable on that object to make it an Parcelable object, only then you can put it in the savedInstanceState by the putParcelable method.

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
  savedInstanceState.putString("my_string", "Welcome back!");
  savedInstanceState.putBoolean("my_boolean", true);
  savedInstanceState.putDouble("my_double", 9.99);
  savedInstanceState.putInt("my_int", 999);
  savedInstanceState.putParcelable("my_parcelable", parcelableObj);
  super.onSaveInstanceState(savedInstanceState);
}

To retrieve the data when the activity is restarted. Make sure the savedInstanceState is not null and then get the data by the names you used when you save them. You can restore the data in the onCreate method or the onRestoreInstanceState method, your choice.

Retrieve the data in onCreate:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  if (savedInstanceState != null) {
	  String 		myString 		= savedInstanceState.getString("my_string");
	  boolean 		myBoolean 		= savedInstanceState.getBoolean("my_boolean");
	  double 		myDouble 		= savedInstanceState.getDouble("my_double");
	  int 			myInt 			= savedInstanceState.getInt("my_int");
	  ParcelableObj ParcelableObj 	= savedInstanceState.getInt("my_parcelable");  
  }
}

Retrieve the data in onRestoreInstanceState:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  if (savedInstanceState == null) return;

  String 		myString 		= savedInstanceState.getString("my_string");
  boolean 		myBoolean 		= savedInstanceState.getBoolean("my_boolean");
  double 		myDouble 		= savedInstanceState.getDouble("my_double");
  int 			myInt 			= savedInstanceState.getInt("my_int");
  ParcelableObj ParcelableObj 	= savedInstanceState.getInt("my_parcelable");
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search