SharedPreferences in Android :

Android provides the SharedPreferences object to assist you save simple application information. using the SharedPreferences object, you’ll save the data you want through the use of key/value pairs — specify a key for the data you want to save, then both it and its value are going to be saved automatically to an XML file.

Android SharedPreferences example

its very useful when storing UI state, user preferences, or application settings, you want a light-weight mechanism to store a known set of values. Shared Preferences allow you to save groups of name/value pairs of primitive data as named preferences.

Creating and saving Shared Preferences :

Using the SharedPreferences class, you’ll create named maps of name/value pairs which will be persisted across sessions and shared among application components running inside the same application sandbox.
To create or modify a Shared Preference, call getSharedPreferences on the present Context, passing within the name of the Shared Preference to change.

To Save or modify a data in Shared Preference, use the SharedPreferences.Editor class. Get the Editor object by calling edit on the Shared Preferences object you want to change.

1. Store Data In Shared Preference :

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

To save data, call apply or commit on the Editor object to save the changes asynchronously or synchronously, respectively.

2. Retrieving Data in Shared Preferences :

Accessing Shared Preferences, like editing and saving them, is done using the getSharedPreferences method.

3. Clear/Delete Data from shared Preference :

Android SharedPreferences Example :

1. Open “” file and add following JAVA code.

File : src/package-name/

Before using the SharedPreferences object, use the getSharedPreferences() method to obtain an instance of the SharedPreferences object, passing it the name of the preference file, as well as the operating mode (MODE_PRIVATE is the default):

2. Open “res/layout/activity_main.xml” file and put this xml code it into file:

File : res/layout/activity_main.xml

 Output of  Android  SharedPreferences Example in emulator :

Android Shared Preferences example

Download Android SharedPreferences example Source code :

Note : This example (Project) is developed in Eclipse Version Kepler,tested on Android 4.4.2 (KitKat Version) and SDK build-tools 23.0

Leave a Reply