Android Persist Data Using Shared Preferences

Most of the projects need to persist different data in order to use it in a way or another. So in this tutorial I will show you how to persist your data using Shared Preferences in Android.

First you have to know that in Android, if you need to store data you have 4 options to achieve this:
1. Using Shared Preferences
2. Using SQLite Databases (for this option you have to install SQLite Browser or other)
3. Using Internal Storage
4. Using External Storage

But in the today’s tutorial we will see how to use the first option: Shared Preferences. So let’s start :)

Before we jump to the code you should know a few things about Shared Preferences.  Shared Preferences allows you to persist key-value pairs of primitive data types which means that this type of storage is used only when we need to persist simple, few information. For more complex data you should use the second type of storage (SQLite Databases)

1. Create a new project and call it Preferences like me, for simplicity and name your main activity “MyActivity”
2. Go to res-layout-main and make 2 buttons

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Hello World, MyActivity"/>

<Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:text="MY BUTTON"/>

<Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show_saved_data"
        android:text="SHOW SAVED DATA"/>
</LinearLayout>

3. Go to MyActivity class and put this code:

package com.example;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MyActivity extends Activity
{
    private Button mMyButton;
    private Button mShow;
    private String mDataString;
    private String mGetSavedData;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mMyButton = (Button)findViewById(R.id.button);
        mShow = (Button)findViewById(R.id.show_saved_data);

        //restore the saved data
        SharedPreferences preferences = getSharedPreferences("pref", 0);
        mGetSavedData = preferences.getString("savedData", "default value");

        mMyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //in mDataString we put the name of mMyButton when we click it
                mDataString = mMyButton.getText().toString();
            }
        });

        mShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MyActivity.this, mGetSavedData,1).show();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();

        //save the data
        SharedPreferences preferences = getSharedPreferences("pref", 0);
        SharedPreferences.Editor editor = preferences.edit();

        //"savedData" is the key that we will use in onCreate to get the saved data 
        //mDataString is the string we want to save
        editor.putString("savedData", mDataString);

        // commit the edits
        editor.commit();

    }
}

NOTE: the “pref” key and “savedData” key must be the same in onPause and in onCreate. The “default value” from mGetSavedData = preferences.getString(“savedData”, “default value”);
represents the value to return if the value does not exist.

4. Now run your application and  click first the “Show Saved Data” button. You will see the default value like in the picture below, because you didn’t exit the application so the onPause to be called. This step is just to see the difference between saved data and unsaved data.

5. Click the button “MY BUTTON”. Now in the string mDataString you must have the name of the button.

6. Now press the back button. At this step the onPause was called and the mDataString is stored.

7. Reopen the application and press the “SHOW SAVED DATA” and you will must see the name of “MY BUTTON” like in the picture below.

As you could see it’s not very hard use Shared Preferences in order to persist data.
Scroll to Top