Tutorial

Android Shared Preferences Example Tutorial

Published on August 3, 2022
author

Anupam Chugh

Android Shared Preferences Example Tutorial

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

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

Initialization

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.clear();
editor.commit(); // commit changes

Project Structure

android-shared-preferences-project-view

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="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="Save"
        android:text="Save" />

    <Button
        android:id="@+id/btnRetr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="Get"
        android:text="Retrieve" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/etEmail"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="clear"
        android:text="Clear" />

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/etName"
        android:layout_marginTop="20dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="text"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/etEmail"
        android:layout_alignStart="@+id/etEmail" />

</RelativeLayout>

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

package com.journaldev.sharedpreferences;

import android.app.Activity;
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";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);
        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);
        editor.commit();
    }

    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        name.setText("");
        email.setText("");

    }

    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

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

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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: android-shared-preference-example This brings an end to this tutorial. You can download the project Android Shared Preferences from the below link.

Download Android Shared Preferences Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 30, 2021

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.

- Ajith

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 30, 2020

    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.

    - Ravindra

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 6, 2020

      How can a list be saved?

      - Desean

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 19, 2020

        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.

        - Fernando

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 17, 2020

          hello, thank you help me with this good tuto ^^

          - olivier.b

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            March 12, 2020

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

            - nat

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 30, 2019

              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”;

              - Onkokame

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                October 18, 2019

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

                - Aditya Shah

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 10, 2019

                  Thanks sir

                  - Aung Htet

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    June 24, 2019

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

                    - zain

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.