Tutorials Android How to Save Android Application’s Activity State

How to Save Android Application’s Activity State

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");
Inline Feedbacks
View all comments
Previous Post

Bootstrap Navigation Tabs with Dropdown Menu Example

Next Post

How to Programmatically Take a Screenshot in Android?

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
Would love your thoughts, please comment.x