Android Shared Preferences Tutorial

Advertisements


Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.

In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);	

The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes availaible that are listed below:

Sr. NOMode and description
1MODE_APPEND
This will append the new preferences with the already exisiting preferences
2MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance has already been loaded
4MODE_PRIVATE
By setting this mode , the file can only be accessed using calling application
5MODE_WORLD_READABLE
This mode allow other application to read the preferences
6MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences

You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will recieve it in an editor object. Its syntax is:

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data inside shared preferences. They are listed as follows:

Sr. NOMode and description
1apply()
It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling
2clear()
It will remove all values from the editor
3remove(String key)
It will remove the value whose key has been passed as a parameter
4putLong(String key, long value)
It will save a long value in a preference editor
5putInt(String key, int value)
It will save a integer value in a preference editor
6putFloat(String key, float value)
It will save a float value in a preference editor

Example

This example demonstrates the use of the Shared Preferences. It display a screen with some text fields , whose value are saved when the application is closed and brought back when it is opened again .

To experiment with this example , you need to run this on an actual device on after developing the application according to the steps below:

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as SharedPreferences under a package com.example.sharedpreferences. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add progress code to display the spinning progress dialog.
3Modify res/layout/activity_main.xml file to add respective XML code.
4Modify res/values/string.xml file to add a message as a string constant.
5Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modified main activity file src/com.example.sharedpreferences/MainActivity.java.

package com.example.sharedpreferences;

import com.example.sharedpreferences.*;

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 {

   TextView name ;
   TextView phone;
   TextView email;
   TextView street;
   TextView place;
   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey"; 
   public static final String Phone = "phoneKey"; 
   public static final String Email = "emailKey"; 
   public static final String Street = "streetKey"; 
   public static final String Place = "placeKey"; 

   SharedPreferences sharedpreferences;

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

      name = (TextView) findViewById(R.id.editTextName);
      phone = (TextView) findViewById(R.id.editTextPhone);
      email = (TextView) findViewById(R.id.editTextStreet);
      street = (TextView) findViewById(R.id.editTextEmail);
      place = (TextView) findViewById(R.id.editTextCity);

      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

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

      }
      if (sharedpreferences.contains(Phone))
      {
         phone.setText(sharedpreferences.getString(Phone, ""));

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

      }
      if (sharedpreferences.contains(Street))
      {
         street.setText(sharedpreferences.getString(Street, ""));

      }
      if (sharedpreferences.contains(Place))
      {
         place.setText(sharedpreferences.getString(Place,""));

      }

   }

   public void run(View view){
      String n  = name.getText().toString();
      String ph  = phone.getText().toString();
      String e  = email.getText().toString();
      String s  = street.getText().toString();
      String p  = place.getText().toString();
      Editor editor = sharedpreferences.edit();
      editor.putString(Name, n);
      editor.putString(Phone, ph);
      editor.putString(Email, e);
      editor.putString(Street, s);
      editor.putString(Place, p);

      editor.commit(); 

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

}

Following is the content of the modified main activity file res/layout/activiy_main.xml.


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/scrollView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      tools:context=".DisplayContact" >

<RelativeLayout
   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"
   >

   <EditText
      android:id="@+id/editTextName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_marginTop="5dp"
      android:layout_marginLeft="82dp"
      android:ems="10"
      android:inputType="text" >

   </EditText>

   <EditText
      android:id="@+id/editTextEmail"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextStreet"
      android:layout_below="@+id/editTextStreet"
      android:layout_marginTop="22dp"
      android:ems="10"
      android:inputType="textEmailAddress" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editTextName"
      android:layout_alignParentLeft="true"
      android:text="@string/name"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextCity"
      android:layout_alignParentBottom="true"
      android:layout_marginBottom="28dp"
      android:onClick="run"
      android:text="@string/save" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editTextEmail"
      android:layout_alignLeft="@+id/textView1"
      android:text="@string/email"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <TextView
      android:id="@+id/textView5" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editTextPhone"
      android:layout_alignLeft="@+id/textView1"
      android:text="@string/phone"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <TextView
      android:id="@+id/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/editTextEmail"
      android:layout_alignLeft="@+id/textView5"
      android:text="@string/street"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editTextCity"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/editTextName"
      android:layout_below="@+id/editTextEmail"
      android:layout_marginTop="30dp"
      android:ems="10"
      android:inputType="text" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/editTextCity"
      android:layout_alignBottom="@+id/editTextCity"
      android:layout_alignParentLeft="true"
      android:layout_toLeftOf="@+id/editTextEmail"
      android:text="@string/country"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editTextStreet"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextName"
      android:layout_below="@+id/editTextPhone"
      android:ems="10"
      android:inputType="text" >

      <requestFocus />
   </EditText>

   <EditText
      android:id="@+id/editTextPhone"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextStreet"
      android:layout_below="@+id/editTextName"
      android:ems="10"
      android:inputType="phone|text" />

   </RelativeLayout>

   </ScrollView>
  

Following is the content of the modified content of file res/values/strings.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">SharedPreferences</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>

   <string name="name">Name</string>
   <string name="phone">Phone</string>
   <string name="email">Email</string>
   <string name="street">Street</string>
   <string name="country">City/State/Zip</string>

   <string name="save">Save Contact</string>

</resources>

Following is the content default file AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sharedpreferences"
   android:versionCode="1"
   android:versionName="1.0" >

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

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.sharedpreferences.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>

</manifest>

Let's try to run your SharedPreferences application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid SharedPreferences Tutorial

Select your mobile device as an option and then check your mobile device which will display following screen:

Anroid SharedPreferences Tutorial

Now just put in some text in the field. Like i put some random name and other information and click on save button.

Anroid SharedPreferences Tutorial

Now when you press save button , the text will be saved in the shared preferences. Now press back button and exit the application. Now open it again and you will see all the text you have written back in your application.

Anroid SharedPreferences Tutorial

Advertisements
Advertisements