Android – How to save Activity State and Persistence data

When beginners starts learning about android development, one of the things that trick them or they found difficult to wrap their head on is how to save Activity State and Android Activity Lifecycle.

Before you understand how to save Activity state in android, you should have an understanding of android lifecycle.

If you are interested to learn more about Android Lifecycle, I suggest you read android developer guide on Activity Lifecycle here.

What is Android Activity State Changes

In android activity state changes can occur as a result of user action or trigger by the android system. Some of the examples of activity state change is

1. Layout configuration change – this is when a device move from portrait to landscape or vice versa

2. When User taps the Back Button – If an activity is in the foreground, and the user taps the Back button, the activity transitions through the onPause(), onStop(), and onDestroy() callbacks. In addition to being destroyed, the activity is also removed from the back stack.

It is important to note that, by default, the onSaveInstanceState() callback does not fire in this case.

Some of the transient data that need to be save on activity state change can be a test input value in EditText widget, select option in RadioButton and so forth.

If you have a look at the second example, you will see that when an Activity is destroy by a user for example by pressing the back button or by android system when it need to allocate more memory to app in forground, the activty is complete removed from the back stack and onSaveInstanceState().

In this case, saving data on onSaveInstanceState() state might not work in your application.

Lets look at how we can save and retrieve data when there is activity state change in android.

android activity state

1. Create a new android app

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidSaveInstance

Package: com.inducesmile.androidsaveinstance

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

2. Add the code below to activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidsaveinstance.MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="@string/select_your_gender" />
    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="16dp"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="24dp"
            android:textSize="10dp"
            android:text="@string/male"/>
        <RadioButton
            android:id="@+id/female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp"
            android:text="@string/female"/>
    </RadioGroup>
</LinearLayout>

 3. Override the onSaveInstanceState(Bundle out) and onRestoreInstanceState(Bundle saveInstance) methods

We will override these two methods mentioned above. The onSaveInstanceState method will be used to save the current selected value of the gender RadioButton. Note that it is better to check the Bundle data in onRestoreInstanceState method than in onCreate since the Bundle in onCreate can return null.

The onRestoreInstanceState method is only called when the Bundle parameter has a stored data.

Open the MainActivity and add the code below.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RadioGroup radioGroup;
    private RadioButton maleRadioButton;
    private RadioButton femaleRadioButton;
    private String selectedGender;
    private static final String GENDER_STATUS = "gender";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        maleRadioButton = (RadioButton)findViewById(R.id.male);
        femaleRadioButton = (RadioButton)findViewById(R.id.female);
        if(!TextUtils.isEmpty(selectedGender)){
            setRadioButtonState();
        }
        radioGroup = (RadioGroup)findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                if(id == R.id.male){
                    selectedGender = "MALE";
                }
                if(id == R.id.female){
                    selectedGender = "FEMALE";
                }
            }
        });
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        selectedGender = savedInstanceState.getString(GENDER_STATUS);
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if(!TextUtils.isEmpty(selectedGender)){
            outState.putString(GENDER_STATUS, selectedGender);
        }
        super.onSaveInstanceState(outState);
    }
    private void setRadioButtonState(){
        if(selectedGender.equals("MALE")){
            maleRadioButton.setChecked(true);
        }
        if(selectedGender.equals("FEMALE")){
            femaleRadioButton.setChecked(true);
        }
    }
}

4. Saving persistence data on Activity State Change

Persistence data in our android application are data we will like to store or save during the onPause() method call so that the user will keep doing what he or she is doing thereafter without losing data.

There are many other ways you can save persistence data in android like using File system or database.

To learn more about this options you can read my tutorials on

ANDROID SQLITE DATABASE EXAMPLE TUTORIAL 

Finally, if you have used another method to achieve this, I will appreciate it if you can share your solution with us.

OTHER INTERESTING POSTS:

Add a Comment