Android SharedPreferences Example Code(Save User Data)

Simple Android SharedPreferences Example with Code Description

Here we will discuss about Android SharedPreferences example with source code and description. That means we will learn about how to store persistent user data in our own Android application and get it back when required. Also we will learn how to add, edit, retrieve (fetch), load, store, delete and update data in Android SharedPreferences. Android provides different options to save persistent application data. It is completely your choices to which option you want to use for your application. Android provides below different data storage options.

  • SharedPreferences

Store your application’s private primitive data (working as key-value pairs).
You can use SharedPreferences to save any primitive data of your application like: boolean, float, int, long, and string etc. This data will persist across user sessions (even if your application is closed or forcible killed by Android OS).

  • SQLite Databases

Store your application’s structured data in your application’s private database. It will store in the application’s context. I have already written a very nice article about how to save application’s data in your own Android SQLite database. Click here to read this article.

  • Network Connection

Store your application’s data on the web with your own network server. So that other users can access it when required.

  • Internal Storage

Store your applications private data on the phone memory (device memory)

  • External Storage

Store your application’s data on the shared external storage, so that other application can be access it if required.

android sharedpreferences example

Now it is enough for some basic idea about data storing in Android. Let’s come to our main focus e.g.  “Android SharedPreferences example with source code description”

To make this Android shared preference example very simple, we will use different Android primitive data types like: boolean, float, int, long, and string etc and store some user data into Android SharedPreference. Then we will retrieve (fetch) those stored data from Android SharedPreferences.

Note: Android SharedPreferences uses only Key-Value pair for storing data, that means, when we will store data to Android SharedPreferences, we will use a unique key and some corrosponding data with that key.

Simple Steps for Android Shared Preferences Use

Step 1: Create a new Shared Preferences file in your Android application. We will open it if it is already exist. We will use the function getSharedPreferences() function from the inbuilt Android class.

Step 2:  For getting data from the Android SharedPreferences file, we will use functions like getString(), getInt() etc.

Step 3:  For storing the data, we need to use the Android Editor Class SharedPreferences.Editor. Then we will store data into the Android SharedPreferences file using functions putString(), putInt() etc. then commit the whole data using commit() function.

Android SharedPreferences Initialization

Android SharedPreferences can be fetch using the function getSharedPreferences()This function need a context (your Activity context). so use your Activity context if you will call this from your activity class. If you call this from a non Activity class like Android services, then first store the context and use it for getSharedPreferences(). Don’t worry we will discuss complete details in below example. this is only for the code snippet. Finally we need an Android editor class to save the changes in the Android SharedPreferences. Below is the code snippet.

First import the below package into your java file, where you want to use shared preference.

Storing Data into Android SharedPreferences

After the above initialization code, we need to follow the below code snippet for storing different types of data in to Android SharedPreferences.

Note: In the above code snippet, to make the code buildable please change “float value”, “long value” to the real float and long values.

Fetching Data from Android SharedPreferences

Data can be fetch from saved preferences by calling getString() (For string), getInt() (for Int) method etc. Note that: these methods should be called using SharedPreferences not using Editor. Below is the code snippet.

 Deleting Data from Android SharedPreferences

If you want to delete some specific data from Android sharedpreferences, then we can call the function remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear() function.

If you want to clear (delete) all data at a time then you can use the below code snippet.

 Create Project: Android SharedPreferences Example

Now coming to the Android SharedPreferences Example. You can use the below example to learn about Android Shared Preferences. We will get some input data (we have used 3 fields : Name, Employee ID and Age) from user. Then we will save it into the shared preferences file, After that we will retrieve those values from the android SharedPreferences file. To make the example very simple, we will use 2 buttons (Store and Load) for this purpose. Also i have implemented a Simple SharedPrefManager Class. which will perform all Android SharedPreferences operations for you. You can use and edit this java file (SharedPrefManager Class) as per your requirement. Only what you need to do is: replace the package name ‘package com.techblogon.sharedpreferenceexample;‘ to your application’s package name.

1. Create a project with project name: SharedPreferenceExample

2. Fill Application Name: SharedPreferenceExample

3. Fill Package Name as: package com.techblogon.sharedpreferenceexample;

4. I have used SDK version Android 4.0.3 and Eclipse Version Indigo. But you can use any version.

5. Add below xml file (activity_main.xml) into your project’s res/layout folder. or you can copy the xml file contents.

This the default xml file in the project. here we used 3 EditText field to get user data to store into the sharedpreferences file. Also added 2 buttons (Store and Load) to make the operation simple.

6. Add below Java file (  in you project’s /src folder.

This file contains a class  ‘SharedPrefManager’, which will handle all Android SharedPreferences operations. You just want to call those functions form where you want to store/load data in to the shared preference.  All functions are static in nature, so no need to create any instance of the class, just call these functions using the class name with .dot operator. For example if you want to save data then just call : SharedPrefManager.StoreToPref();

7. Add the below default Activity Java file (MainActivity.Java) , which contains all GUI part and will use all SharedPreferences functions from this class.

In this class we called SharedPrefManager.Init(this) function from the OnCreate() of the activity. Then we will Store and Load user data when user click on the buttons called Store and Load. Here you can find functions like onClickLoad() and onClickStore(), where we will store and load user data. So first we will get user data and pass all user data to the SharedPrefManager class using it’s own functions, then we will store all data at a time using SharedPrefManager class’s function SharedPrefManager.StoreToPref(). Similarly we will use SharedPrefManager.LoadFromPref().

8. Finally the Manifest File.

9. That’s it. Build and run the application on Android device/emulator.

You can download Android SharedPreferences Example from here.

Tips on Android Shared Preference Uses

Sometimes you might want to delete the old SharedPreferences file. If you want to delete the old one and create a new one, then you need to know the file location where this file is created for your application. Goto DDMS->File Explorer. Please refer to the below image.

android sharedpreferences file location

Some Android SharedPreferences Issues and Solutions

Error: The new data overwrites the old data in Android Shared Preference

Solution: Android calls clear() function, when you save (commit) data. so all your existing data will be erased. To prevent that, first you have to get all old data and save those in some variables, then add you new data and save all at a time. You can use Android Vector and Android Array for this purpose.

Error: Data not saved in Android Shared Preference.

Solution: Sometimes the above issue happens with me also, there are several reasons. However delete the preference file and create a new one might solve your problem. Make sure to save your date before delete.

I hope this tutorial on Android SharedPreferences Example will help you at it’s best.


Post By SmrutiRanjan (57 Posts)

Working @ Samsung as a Project Lead for Android Smartphones. I have been blogging since 2008. Previously I was writing articles for other bloggers, but finally I have started my own blog-"Techblogon".I am also an active contributor for the blog-"Gadgets n Gizmos World". Job is my necessity, but blogging is my passion.

Website: → Techblogon


8 Responses to Android SharedPreferences Example Code(Save User Data)

  1. Anil says:

    Hi SmrutiRanjan,

    I am regular reader of your android tutorial thanks for your tutorial and it’s very useful for me. On the above article you have mention string is primitive date type. Is String is primitive data type in java? or we can userdefind date types into SharedPreferences. Please explain.

    Anil Kumar

    • SmrutiRanjan says:

      Make sure to turn on Auto rotation feature in your phone.
      It will work 100%.

    • SmrutiRanjan says:

      Yes, String is primitive data type in java. you can save in sharedpref.
      User defined data type is nothing but collection of primitive data types, so you can write a small logic ff you want to save user define data types in sharedpref.
      That means, iterate into the user define data type and save individual data. Also for more complex data it is better to use SQLite database

  2. Anil Yadav says:

    Nice Tutorial Dear.

    Can you post how fetch data in android using Json restful web services.

    Because I search on google but not clear.

    Thanks in advance.

  3. Hemant katariya says:

    Hello Sir, Thank you for posting these tutorial.

    Can you help me related to some sample.

    So please upload google map v2 and twitter or facebook tutorial or send me samples. Urgently require

  4. EKTA says:

    sir i need a full code of android in a zip file which will import data that already existing on sqlite database,i want to only retrieve that data.i tried many codes but its not working.

  5. alloice says:

    can i get a code for a shopping cart in android that picks items from the database?????

  6. Sundaramoorthy says:

    I am doing android facebook integration. I need to store authentication information into device account. Anyone help please. Is it possible ??

Leave a Reply

Your email address will not be published. Required fields are marked *

eight − = 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">