TrinityTuts

Working with Shared Preference Android

Last updated on August 12th, 2015 at 11:54 pm

Shared Preference is very useful in android application. Shared preference in android is work like session in your whole app you can access shared preference data any where in your app. Even when user close the application Preference data is saved and you access that data again when user start app.

Before Start creating an application i give you basic introduction of Shared Preference.

Introduction to Shared Preference

Shared Preference allow us to save user data and access that data any where in application. Share Preference also Keep data even when user close the application. Initialization of shared preference in application:

SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);

We use share preference by calling getSharedPreferences(“Data_KEY”, MODE);.  You also need an editor to edit and save the changes in shared preferences.

SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
Editor edit = share.edit();

Storing Data in Shared Preference

We can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.

edit.putBoolean("key_name", true); 
edit.putString("key_name", "string value"); 
edit.putInt("key_name", "int value"); 
edit.putFloat("key_name", "float value");
edit.putLong("key_name", "long value"); 
 
edit.commit();

Retrieving Data

Data can be retrieved from saved preferences by calling getString() (For string) method. Remember this method should be called on Sharedpreferences not on Editor.

share = getSharedPreferences("Data", Context.MODE_PRIVATE);
String sname = share.getString("sName", "NULL");
String semail = share.getString("sEmail", "NULL");

Clearing / Deleting Data

If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()

share = getSharedPreferences("Data", Context.MODE_PRIVATE);
edit = share.edit();
edit.clear();
edit.commit();

Simple Application of Shared Preference

I create a simple application to help you to understand this.

Start your New Android Project

1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. I had left my main activity name as MainActivity.java .

2. Now open your activity_main.xml inside res ⇒ layout folder and create Input fields as shown below image.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="62dp"
        android:text="Name"
        android:gravity="left" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="14dp"
        android:ems="10"
        android:hint="First Last"
        android:inputType="textPersonName"
        android:gravity="center" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/Show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="Show" />

    <Button
        android:id="@+id/Remove"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/Show"
        android:layout_alignBottom="@+id/Show"
        android:layout_centerHorizontal="true"
        android:text="Remove" />

    <EditText
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/Show"
        android:layout_alignLeft="@+id/name"
        android:layout_marginBottom="30dp"
        android:ems="10"
        android:gravity="center"
        android:hint="Email"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/email"
        android:layout_alignBottom="@+id/email"
        android:layout_alignLeft="@+id/Show"
        android:text="Email" />

    <Button
        android:id="@+id/Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/email"
        android:layout_centerVertical="true"
        android:text="Save" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Show"
        android:layout_below="@+id/Show"
        android:layout_marginTop="34dp"
        android:layout_toLeftOf="@+id/Remove"
        android:text="Output"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/Save"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="24dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView4"
        android:layout_alignLeft="@+id/textView3"
        android:text="Name" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView5"
        android:layout_marginTop="37dp"
        android:text="Email" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView6"
        android:layout_alignBottom="@+id/textView6"
        android:layout_alignRight="@+id/textView4"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

3. Now open your MainActivity.java inside src ⇒MainActivity.java. Here we can add data to shared preference, Show saved Data and Remove Data

MainActivity.java

package com.shareprefrence;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	Button show, save, remove;
	SharedPreferences share;
	Editor edit;
	EditText name, email;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Fields
		name = (EditText) findViewById(R.id.name);
		email = (EditText) findViewById(R.id.email);

		// Show Prefrence data
		show = (Button) findViewById(R.id.Show);

		final TextView n = (TextView)findViewById(R.id.textView4);
		final TextView e = (TextView)findViewById(R.id.textView7);
		
		
		show.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				share = getSharedPreferences("Data", Context.MODE_PRIVATE);
				
				String sname = share.getString("sName", "NULL");
				String semail = share.getString("sEmail", "NULL");
				
				
				n.setText(sname);
				e.setText(semail);
				
			}
		});

		// Add value to prefrence
		save = (Button) findViewById(R.id.Save);
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String Name = name.getText().toString();
				String Email = email.getText().toString();

				share = getSharedPreferences("Data", Context.MODE_PRIVATE);
				edit = share.edit();
				edit.putString("sName", Name);
				edit.putString("sEmail", Email);
				edit.commit();

				Toast.makeText(getApplicationContext(), "Done!",
						Toast.LENGTH_LONG).show();
			}
		});

		// Clear saved prefrence
		remove = (Button) findViewById(R.id.Remove);
		remove.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Toast.makeText(getBaseContext(), "Remove",
				// Toast.LENGTH_LONG).show();
				share = getSharedPreferences("Data", Context.MODE_PRIVATE);
				edit = share.edit();
				edit.clear();
				edit.commit();
				
				n.setText("");
				e.setText("");
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

In our activity i create three button (Show, Add, Remove) when user add data to fields and press save we save data to preference.

		// Add value to prefrence
		save = (Button) findViewById(R.id.Save);
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String Name = name.getText().toString();
				String Email = email.getText().toString();

				share = getSharedPreferences("Data", Context.MODE_PRIVATE);
				edit = share.edit();
				edit.putString("sName", Name);
				edit.putString("sEmail", Email);
				edit.commit();

				Toast.makeText(getApplicationContext(), "Done!",
						Toast.LENGTH_LONG).show();
			}
		});

Now data is saved to preference if you want to check saved data click on Show button.

Now if you want to remove this data click on remove button. You can download this application from above download link.

Thank you.