My Life with Android
Introduction Android Componets UserInterface Advanced UI Data Storage Advanced Concepts Others New Studio

1. Shared Preferences

  • Android provides many ways of storing data of an application.One of this way is called Shared Preferences.
  • Android SharedPreferences allows us to store private primitive application data(booleans, floats, ints, longs, and strings.) in the form of key-value pair.
  • Android stores shared preference settings as XML file in shared_prefs folder under DATA/data/[application package] directory.
  • SharedPreferences is application specific, i.e.) the data is lost when you perform one of the options, a) once you uninstall the application and b) once you clear application data (through Settings)

How to get SharedPreferences instance?

In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
SharedPreferences sharedpreferences = getSharedPreferences(My_Pref, Context.MODE_PRIVATE);
Where,
  • My_Pref is the name of the file.
  • Context.MODE_PRIVATE is the operating mode.
MODE_PRIVATE : By setting this mode , the file can only be accessed using calling application.

Here the file is stored as :
DATA/data/[application package name]/shared_prefs/preference_name.xml




2. Storing Data in SharedPreferences

To save a value in SharedPreferences, you can use SharedPreferences.Editor class. Steps:
  1. Get SharedPreferences instance.
  2. Get SharedPreferences.Editor instance by calling edit() method in SharedPreferences instance.
  3. Store values by calling one of the putXXXX() methods.
  4. Commit the editor object.
Its syntax is :

...
public static final String PREFS_NAME = "MY_PREFS";
public static final String PREFS_KEY = "USER_NAME_String";
...
public void save(Context context, String text) {
    SharedPreferences settings;
    Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
    editor = settings.edit(); //2
 
    editor.putString(PREFS_KEY, text); //3
    editor.commit(); //4
}

Only primitive data types can be stored in SharedPreferences. Other methods are,

3. Retrieve Data from SharedPreferences

To get a value from shared preferences, you can use the SharedPreferences class' getXXXX methods without the Editor object.
Steps:
  1. Get SharedPreferences instance.
  2. Call one of the getXXXX() methods using SharedPreferences instance.

...
public static final String PREFS_NAME = "MY_PREFS";
public static final String PREFS_KEY = "MY_PREFS_String";
...
public String getValue(Context context) {
    SharedPreferences settings;
    String text;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
    text = settings.getString(PREFS_KEY, null); //2
    return text;
}

4. Clear SharedPreferences Data

To remove all values from preferences use editor.clear() method as shown below.

...
public static final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_KEY = "AOP_PREFS_String";
...
 
public void clearSharedPreference(Context context) {
    SharedPreferences settings;
    Editor editor;
 
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
 
    editor.clear();
    editor.commit();
}

To remove a specific key-value pair use editor.remove(KEY) method as shown below.

...
public static final String PREFS_NAME = "MY_PREFS";
public static final String PREFS_KEY = "MY_PREFS_String";
...
 
public void removeValue(Context context) {
    SharedPreferences settings;
    Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
 
    editor.remove(PREFS_KEY);
    editor.commit();
}

5. Store,Fetch,Remove,Clear Data from SharedPreferences.


/********** 1. Create SharedPreferences **********/
 
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
    Editor editor = pref.edit();
 
 
/********** 2. Storing data as KEY/VALUE pair **********/
 
    editor.putBoolean("key_name1", true);           // Saving boolean - true/false
    editor.putInt("key_name2", "int value");        // Saving integer
    editor.putFloat("key_name3", "float value");    // Saving float
    editor.putLong("key_name4", "long value");      // Saving long
    editor.putString("key_name5", "string value");  // Saving string
     
    // Save the changes in SharedPreferences
    editor.commit(); // commit changes
 
 
/********** 3. Get SharedPreferences data **********/
 
// If value for key not exist then return second param value - In this case null
 
    pref.getBoolean("key_name1", null);         // getting boolean
    pref.getInt("key_name2", null);             // getting Integer
    pref.getFloat("key_name3", null);           // getting Float
    pref.getLong("key_name4", null);            // getting Long
    pref.getString("key_name5", null);          // getting String
 
 
/********** 4. Deleting Key value from SharedPreferences **********/
 
    editor.remove("key_name3"); // will delete key key_name3
    editor.remove("key_name4"); // will delete key key_name4
     
    // Save the changes in SharedPreferences
    editor.commit(); // commit changes
    
/********** 5. Clear all data from SharedPreferences **********/  

     editor.clear();
     editor.commit(); // commit changes

1. Standard way to access shared preference data

Step 1 : In main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Save" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:text="Get" />

</LinearLayout>

Step 2 : Create your custom SharedPreference class

package com.example.androidex2;

import android.content.Context;
import android.content.SharedPreferences;

public class Preferences {
	private static Preferences yourPreference;
	private SharedPreferences sharedPreferences;
	public static final String USER_NAME = "USER_NAME";

	public static Preferences getInstance(Context context) {
		if (yourPreference == null) {
			yourPreference = new Preferences(context);
		}
		return yourPreference;
	}

	private Preferences(Context context) {
		sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
	}

	public void writeData(String key,String value) {
		SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
		prefsEditor .putString(key, value);
		prefsEditor.commit();           
	}

	public String readData(String key) {
		if (sharedPreferences!= null) {
			return sharedPreferences.getString(key, "");
		}
		return "";         
	}
}

Step 3 : In your MainActivity.java

package com.example.androidex2;

import android.app.Activity;
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 MainActivity extends Activity{
	EditText editText1;
	Preferences yourPrefrence;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		yourPrefrence = Preferences.getInstance(getApplicationContext());
		editText1=(EditText)findViewById(R.id.editText1);
		Button btn=(Button)findViewById(R.id.button1);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				yourPrefrence.writeData(Preferences.USER_NAME,editText1.getText().toString());
			}
		});
		Button btn2=(Button)findViewById(R.id.button2);
		btn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String value = yourPrefrence.readData(Preferences.USER_NAME);
				Toast.makeText(getApplicationContext(), value, Toast.LENGTH_LONG).show();
			}
		});
	}
}

Output

Shared preference example

Step 1 : In main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Save" />

    <Button
        android:id="@+id/btnGet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:text="Get" />

</LinearLayout>

Step 2 : In your MainActivity.java

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
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 MyPreferenceDemo extends Activity{
	EditText editText1;
	SharedPreferences sharedPreferences;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mypreference);
		sharedPreferences = this.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
		editText1=(EditText)findViewById(R.id.editText1);
		Button btnSave=(Button)findViewById(R.id.btnSave);
		btnSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
				prefsEditor.putString("uname", editText1.getText().toString());
				prefsEditor.commit();   
			}
		});
		Button btnGet=(Button)findViewById(R.id.btnGet);
		btnGet.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String value=sharedPreferences.getString("uname", null);
				Toast.makeText(getApplicationContext(), value, Toast.LENGTH_LONG).show();
			}
		});
	}
}

Output