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:

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

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.

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.

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()

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 .

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


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

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


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.