2013-01-11

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

SharedPreferences

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.

Context.MODE_APPENDABLE
If the file already exists then write data to the end,instead of erasing it.

Context.MODE_WORLD_READABLE
Allow all other applications to have read access to the created file.

Context.MODE_WORLD_WRITABLE
Allow all other applications to have write access to the created file.

Editor
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.

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 SharedPreferenceDemo.java file and paste the below code.

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

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 usingSharedPreferences. If you have any queries, please post it in comment section.

Show more