Android Shared Preferences Example Tutorial

Filed Under: Android

In this tutorial we’ll use Shared Preferences in our android application to store data in the form of key-value pair.

Android Shared Preferences Overview

Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory().

SharedPreferences is application specific, i.e. the data is lost on performing one of the following options:

  • on uninstalling the application
  • on clearing the application data (through Settings)

As the name suggests, the primary purpose is to store user-specified configuration details, such as user specific settings, keeping the user logged into the application.

To get access to the preferences, we have three APIs to choose from:

  • getPreferences() : used from within your Activity, to access activity-specific preferences
  • getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences
  • getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework

In this tutorial we’ll go with getSharedPreferences(). The method is defined as follows:

getSharedPreferences (String PREFS_NAME, int mode)

PREFS_NAME is the name of the file.

mode is the operating mode.

Following are the operating modes applicable:

  • MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application
  • MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to cause security holes in applications
  • MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applications
  • MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
  • MODE_APPEND: This will append the new preferences with the already existing preferences
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default


We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences.

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

Storing Data

editor.commit() is used in order to save changes to shared preferences.

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes

Retrieving Data

Data can be retrieved from saved preferences by calling getString() as follows:

pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

Clearing or Deleting Data

remove(“key_name”) is used to delete that particular value.

clear() is used to remove all data

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes

editor.commit(); // commit changes

Project Structure


Android Shared Preferences Project Code

The activity_main.xml layout consists of two EditText views which store and display name and email. The three buttons implement their respective onClicks in the MainActivity.

<RelativeLayout xmlns:android=""
    android:paddingTop="@dimen/activity_vertical_margin" >

        android:text="Save" />

        android:text="Retrieve" />

        android:text="Clear" />

        android:layout_alignParentEnd="true" />

        android:layout_alignStart="@+id/etEmail" />


The file is used to save and retrieve the data through keys.

package com.journaldev.sharedpreferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView email;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";

    protected void onCreate(Bundle savedInstanceState) {
        name = (TextView) findViewById(;
        email = (TextView) findViewById(;
        sharedpreferences = getSharedPreferences(mypreference,
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));



    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);

    public void clear(View view) {
        name = (TextView) findViewById(;
        email = (TextView) findViewById(;


    public void Get(View view) {
        name = (TextView) findViewById(;
        email = (TextView) findViewById(;
        sharedpreferences = getSharedPreferences(mypreference,

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


    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;


mypreference is the name of the file where the shared preferences key-value pair is stored.

The image below shows the final output of our project:


This brings an end to this tutorial. You can download the project Android Shared Preferences from the below link.


  1. Ajith says:

    I have implemented three spinners and one save button. User selects the spinner value, and after pressing the save button, the values will be saved in shared preferences. I don’t know how to get the value from the spinner and display it after opening the application.

  2. Ravindra says:

    Thanks For Explaining Shared Preferences
    I am Activity with the Spin Wheel for coupons. Where User can Spin to get Coupons.

    Now, The Problem is I want to set Daily Limit on that Spin. The Spin Limit will be reset on next day 00:01 hrs.

    I have used shared Preferences, but didn’t worked as expected.
    Please Help me, How could I limit the number of Spins per day.

    1. Anupam says:

      Hi Ravindra,
      Such features should be implemented in the cloud side and not by storing them in local app data. Any user can clear shared preferences and manipulate the data.

  3. Desean says:

    How can a list be saved?

  4. Fernando says:

    I am trying to do something similar, I have a similar structure with EditText and 2 buttons .. The difference is that I have 2 buttons, edit and save. My idea is that when I click the save button, it will show me the data that I enter and cannot be edited and when I click on the edit button, I can edit the data to save again. Could you help me with that or make an example like that.

  5. olivier.b says:

    you help me with this good tuto ^^

  6. nat says:

    But you don’t even call your save() method

    1. Bisharath A K says:

      because the method is declared from the xml. when you click on any button, corresponding methods will call and data will be processed accordingly. For more clarification please check given XML file and find the attribute onclick in each buttons

  7. Onkokame says:

    Good day,
    What is the purpose of the following;

    public static final String mypreference = “mypref”;
    public static final String Name = “nameKey”;
    public static final String Email = “emailKey”;

  8. Aditya Shah says:

    Why there is no onclicklistener method for three buttons? i tried this example but it is still working how??

    1. Anupam says:

      Hi Aditya,
      OnClick Listeners are defined in the XML in this example.


      1. David says:

        I didn’t know you could do that :’)
        Thank you

  9. Aung Htet says:

    Thanks sir

  10. zain says:

    getMenuInflater().inflate(, menu); showing error how to resolve that

  11. J.P. says:

    The downloaded example doesn’t work.
    I added google to the list of repositories and changed the class path to the minimum supported gradle version. It still doesn’t work .

    1. Anupam says:

      What’s the error that you are getting?

  12. Maryam says:

    I have tried your example for textview and it works perfectly.
    The only problem i have is if i wan’t to add checkbox. It’s not saving for me.
    Can you do an example for checkbox ?

    1. Abdullah khan says:

      Mam you can use boolean preference for checkboxes and radio buttons

  13. Maryam says:

    Thank you very much. This is the first Example that works for me.
    But how can i integrate a checkbox in this example? Checkbox, if checked safe checked, if unchecked safe unchecked. If i add my checkbox with safe function your example not safing anymore.

  14. Saransh Agarwal says:

    How to fetch the email ID on the next Activity.

    1. Anupam says:

      Do a getString on the Shared Preferences instance and set the same key that you’d used before.

    2. Ali Rizwan says:

      Do a getString on the Shared Preferences instance and set the same key that you’d used before.And one thing is also update the mode_private changed into Mode_World_Readable..

  15. Rao Diya says:

    Hi sir, thanks for step by step guide.

    pref.getInt(“key_name”, null); // getting Integer

    For this I am getting error in my android app

    “Found null, required int – 2nd argument”

    Please guide me. Thanks

    1. Anupam says:

      Pass an integer instead of null in the second argument.

  16. yucel ozyazgan says:

    Thanks a lot ..! It helped me to understand its usage 🙂

    1. Cuong says:

      Thanks, all your posts are clearly, simple…

  17. Akash Batham says:

    Helped allot in understanding a simple concept, it’ll help in saving my games score.

  18. Jilson says:

    Thank you so much for your great work….

    1. Anupam says:

      Appreciate that!

  19. Nipa says:

    Nice tutorial, but does the function save work when you click button save
    in other words, how did you handle the save button

    1. Anupam says:

      commit() or apply() is used to save the values set in the SharedPreferences Editor.

  20. Rohit Reddy says:

    Nice tutorial to follow. Helped a lot Thanks Anupam

    1. Anupam says:

      Glad it helped you, Rohit.

      1. Abhishek says:

        How do i retreive my data from a fragment??

  21. مجتبی says:

    nice job , Great , Thanks

  22. Ionut Moisoni says:

    Thanks a lot!!!

  23. SELVAM M says:

    this is better for us

  24. Jot Jassal says:

    what is the use of
    public boolean onCreateOptionsMenu(Menu menu)
    getMenuInflater().inflate(, menu);
    return true;

    method in this java file?

    1. KawaiiLovah says:

      This is for OptionMenu .. I guess he just added it coz it was together in his program.. It doesn’t concern with this SharedPreference example..

    2. yogesh says:

      onCreateOptionsMenu(Menu menu) this method is used for adding items in toolbar/actionbar.

  25. nabila says:

    Is this can display the entered name and email in another layout?

    1. nabila says:

      If no, how can I do that?

      1. Rahul Mishra says:

        It can. As shared preference is a common file for an entire app so different activity won’t matter. Use the getSharedPreferences() function in another activity and you are good to use details saved in that file. Just make sure to use the same key as it is case sensitive. Regards.

  26. karthikeyan says:

    this is very useful for us.
    thank you.

  27. sounder says:

    i tried this codes its not working properly

    1. Anupam says:

      Can you let me know the problem you’re facing?

      1. chenchaiah says:

        In xml you take edittext text values …After in activity class you mentiton textview ids…

        1. Anupam says:

          Hi chenchaiah,
          Thanks for pointing that out. The project source code is now updated.

          1. Javier says:

            Could you please publish the apk file? Thank you very much.

          2. Anupam says:

            Hi Javier,
            You can build it from the Android Studio Project. Build -> Build APK.

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content