Shared Preferences in android

In mobile application development each and every small information cannot be stored in a database, as complex database queries can limit the processing power of the processor affecting the battery life.  Android provides a simple mechanism called “Shared Preferences” using which small and vital information like user preferences and others can be stored .

Android data storage options are as follows,

  • Shared Preferences
  • SQLite Database
  • Internal storage
  • External Storage
  • Network connection
  • Content providers

This tutorial explains you how to store and retrieve data using Shared Preferences in android.


Shared Preferences provide a light weight mechanisms where data is saved in the form of KEY-VALUE pair. Sharing user preferences, settings, UI states requires a light weight mechanism rather than a fully fledged database. Shared preferences are used to store private primitive data. The types of data that can be stored are boolean, int, long, float, String. The data that is stored using shared preferences will persist across user sessions even if your application is killed.

Working of Shared Preferences

  • Creating shared preferences actually creates a xml file automatically.
  • XML parsing is not required to deal with the shared preferences.
  • The shared preference APIs are used to make changes to the automatically created XML files.
  • These XML files contain the KEY-VLAUE pairs.
  • Only primitive data types can be added and retrieved from these XMLs.

Shared Preference API


public SharedPreference getSharedPreferences(String name, int mode)

  •  name-name of auto generated XML file.
  • mode is the file creation mode.

The different file creation mode are,

  • Context.MODE_PRIVATE
    the default mode,file can only be accessed by the calling application or any application sharing the same userID.
    If the file already exists then write data to the end,instead of erasing it.
    Allow all other applications to have read access to the created file.
    Allow all other applications to have write access to the created file.

used for modifying values in a SharedPreferences object.

Steps to store and retrieve data using SharedPreferences

Step 1: Get a SharedPreference object for your application using,

  • getSharedPreference()-used if your activity needs mutiple preference files identified by name that you specify with the first parameter.
  • getPreferences()-used if you need only one preference file for your Activity. No name parameter is needed here.

Step 2: Call edit() to get a SharedPreferences.Editor to write values.
Step 3: Add values with methods such as putBoolean() and putString().
Step 4: Commit the new values with the commit() method. All changes you make in an editor are Batched. They are not copied back to the SharedPreferences or persist storage till you call commit().
Step 5: To read the values that you have stored, use SharedPreferences methods such as getBoolen() and getString().

Let us now look at a simple example on how to store and retrieve data using SharedPreferences in android.

Step 1: Set up the android working Environment. If you want to know about how to set up the android environment, please refer to one of our articles Android Environment. I would be using android 2.2 for this example.

Step 2: Create the project.

Create a project My_SharedPreferences with the Activity “SharedPreferenceDemo”. If you have any doubt on how to create a sample project, please go through the post Simple android app.

Step 3: Creating required layout

I would be using the main.xml layout file which gets created automatically when you create your application. Open your main.xml file and paste the below code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="<a href=""></a>">
<EditText android:id="@+id/EditText01" android:layout_height="50dip"
android:text="Hi, Welcome" android:layout_width="200dip"></EditText>
<Button android:id="@+id/Button01" android:layout_below="@id/EditText01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
<Button android:id="@+id/Button02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@+id/Button01"
android:layout_below="@+id/EditText01" android:text="Load"></Button>

As you can see in the above layout file, main.xml contains a layout file which in turn contains an EditText which has a default text “Hi Welcome” and two buttons named “save” and load.

Working of this example:

The edittext first contains a default text “Hi Welcome” which gets stored in the sharedPreference xml file on click of save button. The saved data is set to the Edittext on click of the load button.

Step 4: Create Activities

In this sample App I would be using the launcher activity SharedPreferenceDemo. If you have any doubts on how to create a new activity, please refer to the post Activity.

Open your file and paste the below code.

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferenceDemo extends Activity {

//Name of your XML file which gets created automatically
public static final String FILENAME="ShareDATA";
//Key name
public static final String KEYNAME="key";
private SharedPreferences sharedpreference;
EditText edittext;
Button save,load;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {


//Saving data on click of save button
save.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
//getting object of SharedPreferences
sharedpreference=getSharedPreferences(FILENAME, MODE_PRIVATE);
//taking reference to editor
Editor editor=sharedpreference.edit();
//saving data in editext as key-value pair
//call commit() to save your data
//finally set the clear the editext data
catch (Throwable e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG);

//retrieving data on click of load button

load.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
sharedpreference=getSharedPreferences(FILENAME, MODE_PRIVATE);
//set the edittext to the save data content
edittext.setText(sharedpreference.getString(KEYNAME, "No value Stored"));

catch (Exception f) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), f.toString(), Toast.LENGTH_LONG);



Step 5: Declare the activities in AndroidManifest.xml

Your launcher activity will be automatically declared. If you want to know more about manifest file, please refer to the post AndroidManifest.

Your manifest file contains the below code.

Step 6: Run your application

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="<a href=""></a>"
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SharedPreferenceDemo"
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

<uses-sdk android:minSdkVersion="8" />


Select your application “My_SharedPreferences”->Run As->Android Application

Your first activity “SharedPreferenceDemo” opens up as below.


Click on Save that saves the data and clears the edittext as below.


Now click on load button that sets the data back to the edittext. It is better to write the code that stores the data in activities onPause() method as this is the one which is called when the activity is killed. And write the code to retrieve the data in onResume() since it is the method called when the activity is loaded. This is how you can save and retrieve data using SharedPreferences. If you have any queries, please post it in comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!