Use SharedPreferences in Android

Introduction

 
In this article, we will learn how to develop “remember me check” with functionality in Android.
  • In Android usually, we need to persist user session credentials in our application where user session credentials contain the username, email, password and so on.
     
  • Using SharedPreferences we can store application preferences data persistently.
     
  • In other words, data won't be lost until the application is uninstalled because the preferences data can be stored as key/value pairs and are available across all the Activities of the application or to a specific Activity. 
     
  • Application preferences data will be available even when the device starts or stops (the user closes the app and re-open it).
     
  • SharedPreferences is used to store primitive data-types

Boolean, float, int, long, string

 
SharedPreferences can be used to store data across all the applications or to the specific activity.
  1. getSharedPreferences()- Preferences persisted across all over the application by the name passed to it as a first argument.
     
  2. getPreferences()- Preferences persisted for a specific Activity so there is no need to specify the name since there will be only one file for the activity.
For instance-
  1. private SharedPreferences savePreferences;  
  2. savePreferences = getSharedPreferences("savePrefs"0);  
Instead of 0 we can use Context.MODE_PRIVATE.
 
We can store as many preferences as we want for our application and all of them will continue to be saved in the savePrefs.xml file because we gave the name “savePrefs” in getSharedPreferences.
 
The savePrefs.xml file is usually located at,
  1. /data/data/[package name]/shared_prefs/savePrefs.xml 
Also we can browse it in the File Explorer in the DDMS view.
 
For instance,
 
login xml
 

1. Setting or Updating Preferences

 
To set primitive data, Sharedpreferences has some methods, for instance,
  1. putBoolean(), putInt(), putFloat(), putString() and so on. 
Method
  1. private SharedPreferences savePreferences;    
  2. private SharedPreferences.Editor savePrefsEditor;    
  3. savePreferences = getSharedPreferences("savePrefs"0);    
  4. savePrefsEditor = savePreferences.edit();    
  5.     
  6. //If remember me checkbox is checked    
  7. if (saveDetailsCheck.isChecked()) {    
  8.     //Set the data    
  9.     savePrefsEditor.putBoolean("saveLogin"true);    
  10.     savePrefsEditor.putString("username", username);    
  11.     savePrefsEditor.putString("password", email);    
  12.     //Commit the changes    
  13.     savePrefsEditor.commit();    
  14.     Toast.makeText(getApplicationContext(), "Your details have been saved.", Toast.LENGTH_LONG).show();    
  15. }   

    2. Fetching Preferences

     
    For fetching purposes, the object of SharedPreferences is directly used. There is no need for SharedPreferences.Editor.
     
    There are the following methods,
    1. getBoolean(), getFloat(), getInt(), getLong(), getString() 
    Method
    1. private Boolean saveLogin;    
    2. saveLogin = savePreferences.getBoolean("saveLogin"false);    
    3. if (saveLogin == true)    
    4. {    
    5.    UserName.setText(savePreferences.getString("username"""));    
    6.    Email.setText(savePreferences.getString("password"""));    
    7.    saveDetailsCheck.setChecked(true);    
    8. }   
      Note- Get methods to have two arguments where the first is the name of the key whereas the second one is the default value to return if the preference does not exist.
       
      3. Clear Preferences
      1. //Clear Shared Preferences    
      2. savePrefsEditor.clear();    
      3. savePrefsEditor.commit();   
        Source Code
        1. MainActivity.java    
        2.     
        3. package com.example.loginpreferencesdemo;    
        4.     
        5. import android.app.Activity;    
        6. import android.content.SharedPreferences;    
        7. import android.os.Bundle;    
        8. import android.view.View;    
        9. import android.widget.Button;    
        10. import android.widget.CheckBox;    
        11. import android.widget.EditText;    
        12. import android.widget.Toast;    
        13.     
        14. public class MainActivity extends Activity {    
        15.     EditText UserName, Email;    
        16.     Button Save;    
        17.     String username;    
        18.     String email;    
        19.     
        20.     private CheckBox saveDetailsCheck;    
        21.     private SharedPreferences savePreferences;    
        22.     private SharedPreferences.Editor savePrefsEditor;    
        23.     private Boolean saveLogin;    
        24.     
        25.     @Override    
        26.     protected void onCreate(Bundle savedInstanceState) {    
        27.         super.onCreate(savedInstanceState);    
        28.     
        29.         setContentView(R.layout.fragment_main);    
        30.     
        31.         UserName = (EditText) findViewById(R.id.editText1);    
        32.         Email = (EditText) findViewById(R.id.editText2);    
        33.         Save = (Button) findViewById(R.id.button1);    
        34.     
        35.         saveDetailsCheck = (CheckBox) findViewById(R.id.checkBox1);    
        36.     
        37.         savePreferences = getSharedPreferences("savePrefs"0);    
        38.         savePrefsEditor = savePreferences.edit();    
        39.     
        40.         saveLogin = savePreferences.getBoolean("saveLogin"false);    
        41.         if (saveLogin == true)    
        42.     
        43.         {    
        44.             UserName.setText(savePreferences.getString("username"""));    
        45.             Email.setText(savePreferences.getString("password"""));    
        46.             saveDetailsCheck.setChecked(true);    
        47.         }    
        48.     
        49.         Save.setOnClickListener(new View.OnClickListener() {    
        50.     
        51.             @Override    
        52.             public void onClick(View v) {    
        53.                 // TODO Auto-generated method stub    
        54.                 username = UserName.getText().toString();    
        55.                 email = Email.getText().toString();    
        56.     
        57.                 if (saveDetailsCheck.isChecked()) {    
        58.                     savePrefsEditor.putBoolean("saveLogin"true);    
        59.                     savePrefsEditor.putString("username", username);    
        60.                     savePrefsEditor.putString("password", email);    
        61.                     savePrefsEditor.commit();    
        62.                     Toast.makeText(getApplicationContext(), "Your details have been saved.", Toast.LENGTH_LONG).show();    
        63.     
        64.                 } else {    
        65.     
        66.                     savePrefsEditor.clear();    
        67.                     savePrefsEditor.commit();    
        68.     
        69.                 }    
        70.             }    
        71.         });    
        72.     }    
        73.     
        74. }   
          fragment_main.xml
          1. <RelativeLayout    
          2.     xmlns:android="http://schemas.android.com/apk/res/android"    
          3.     xmlns:tools="http://schemas.android.com/tools"    
          4.     android:layout_width="match_parent"    
          5.     android:layout_height="match_parent"    
          6.     android:paddingBottom="@dimen/activity_vertical_margin"    
          7.     android:paddingLeft="@dimen/activity_horizontal_margin"    
          8.     android:paddingRight="@dimen/activity_horizontal_margin"    
          9.     android:paddingTop="@dimen/activity_vertical_margin"    
          10.     tools:context="com.example.loginpreferencesdemo.MainActivity$PlaceholderFragment" >    
          11.     <TextView    
          12.         android:id="@+id/textView1"    
          13.         android:layout_width="wrap_content"    
          14.         android:layout_height="wrap_content"    
          15.         android:text="Shared Preferences Demo By Abhijeet" />    
          16.     <EditText    
          17.         android:id="@+id/editText1"    
          18.         android:layout_width="wrap_content"    
          19.         android:layout_height="wrap_content"    
          20.         android:layout_alignLeft="@+id/textView1"    
          21.         android:layout_below="@+id/textView1"    
          22.         android:layout_marginTop="60dp"    
          23.         android:ems="10"    
          24.         android:hint="UserName" ></EditText>    
          25.     <EditText    
          26.         android:id="@+id/editText2"    
          27.         android:layout_width="wrap_content"    
          28.         android:layout_height="wrap_content"    
          29.         android:layout_alignLeft="@+id/editText1"    
          30.         android:layout_below="@+id/editText1"    
          31.         android:layout_marginTop="26dp"    
          32.         android:ems="10"    
          33.         android:hint="Email ID" />    
          34.     <Button    
          35.         android:id="@+id/button1"    
          36.         android:layout_width="wrap_content"    
          37.         android:layout_height="wrap_content"    
          38.         android:layout_alignLeft="@+id/editText2"    
          39.         android:layout_below="@+id/editText2"    
          40.         android:layout_marginTop="34dp"    
          41.         android:text="Save Details" />    
          42.     <CheckBox    
          43.         android:id="@+id/checkBox1"    
          44.         android:layout_width="wrap_content"    
          45.         android:layout_height="wrap_content"    
          46.         android:layout_alignRight="@+id/editText2"    
          47.         android:layout_below="@+id/editText2"    
          48.         android:text="Remember Me" />    
          49. </RelativeLayout>   
          Output
           
          Before doing that remember to check:
           
          save detail
           
          After remember to check:
           
          login