Android Shared Preferences example and tutorial


Introduction
           Most Android apps needs  to save data about the application state so that users progress is not lost. SharedPreferences API in android lets us to save data in key-value sets. When there is a need to save small collection of key-values we should use Android SharedPreferences.
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.
        Now lets see how to implement Shared preferences in android with simple example and tutorial.
In this tutorial, we will save object i.e., key-value pairs, to shared preference and retrieve them. We will store Name and email in this example.

Step 1
          To use android shared preference we have to call method  getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences. The first parameter is the key and the second parameter is the MODE as shown below,
sharedpreferences = getSharedPreferences(mypreference,Context.MODE_PRIVATE);

Step 2 : Save object to sharedpreferences
         We can save data to sharedpreferences using SharedPreferences.Editor class, for which we need to use edit method of the shared preference.
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();

Step 3 : Get data from sharedpreference
          sharedpreferences.getString() method should be used to get the values for corresponding keys as shown below

if (sharedpreferences.contains(Name)) {
sharedpreferences.getString(Name, "");
}
if (sharedpreferences.contains(Email)) {
sharedpreferences.getString(Email, "");

}
So basically using these get and put methods in shared preference we can perform this save and retrieval functionality as we wish.
Now Run the program and operate on Save, get and Clear buttons. Save button will save data into shared preference, Get button will retrieve data from Shared preference and clear button will just clear the text from EditText field.

SAVE
GET
CLEAR

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="370dp"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_centerVertical="true"
        android:onClick="Save"
        android:text="Save" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="Get"
        android:text="Get" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/etEmail"
        android:layout_alignBottom="@+id/etEmail"
        android:layout_alignLeft="@+id/textView1"
        android:text="Email"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/etEmail"
        android:layout_centerVertical="true"
        android:layout_marginRight="21dp"
        android:onClick="clear"
        android:text="Clear" />

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="36dp"
        android:ems="10"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/etEmail"
        android:layout_alignLeft="@+id/etEmail"
        android:ems="10"
        android:inputType="text" />

    <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_marginLeft="17dp"
        android:layout_marginTop="39dp"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />


</RelativeLayout>

MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));

}

}

public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}

public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");

}

public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);

if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));

}
}

@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;
}


}

Source code of this application
AndroidSharedPreferences.zip




Reactions:

0 comments :

Post a Comment