What is Shared Preference?

As we all know that storing data is much important in terms of applications or websites anything. While it comes to android applications we have one of the way to store data of users is Shared Preference. It will store data globally, it means we can use this data anywhere in whole application.

The data will be store in key-value pair. For example, EmailId = example@gmail.com. Shared Preference allows to read and write data of ints, strings, floats, booleans and longs data types. Data will be stored globally and will not be removed even if user close the application. You can store data such as UserId, Emailid, user’s selected ringtone etc… in the form of key-value pair.

To read and write data into Shared Preference you have to use its getSharedPreferences() method. Let’s see how to store and retrieve data using Shared Preference.

Storing data into Shared Preference

I have created Android Project which contains the screen with some EditText and Button. Which help us to store and retrieve data from Shared Preference.

Step 1. Create Android Project with an empty Activity called MainActivity.  As we have created Activity, two files activity_main.xml and MainActivity.java will be created in its correspondent folders. See project structure given at end of this blog. I have created project with name SharedPreferenceExample.

Modify activity_main.xml file according to your requirements. I have created login form by which we will store user session into Shared Preference and display his/her username on next activity. Also we provide logout option to remove Shared Preference.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:gravity="center_horizontal"

    android:orientation="vertical"

    android:padding="15dp"

    tools:context=".MainActivity">

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="15dp"

        android:text="Login To My App"

        android:textSize="20dp"

        android:textStyle="bold" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Username"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <EditText

        android:id="@+id/edtLogUsername"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:fontFamily="sans-serif"

        android:hint="Enter Username"

        android:padding="10dp" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Password"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <EditText

        android:id="@+id/edtLogPassword"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:fontFamily="sans-serif"

        android:hint="Enter Password"

        android:inputType="textPassword"

        android:padding="10dp" />

  

    <Button

        android:id="@+id/btnLogin"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Login" />

  

</LinearLayout>

Step 2. Open MainActivity.java, modify it by writing below code to store data. I have used admin-admin as username and password to login. You can use username and password from your database. Please read out all the comments which I have mentioned in code to understand it properly.

MainActivity.java

package com.example.sharedpreferenceexample;

  

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

  

public class MainActivity extends AppCompatActivity {

  

    /* Declare object to store controls of activity_main.xml file */

    EditText edtLogUsername, edtLogPassword;

    Button btnLogin;

  

    /* Final variables */

    public static final String PreferencesName = "AppPref";

  

    /* Declare object of SharedPreferences */

    SharedPreferences sharedPreferences;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

  

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        /* Find controls from activity_main.xml file and initialize it to object */

        edtLogUsername = (EditText) findViewById(R.id.edtLogUsername);

        edtLogPassword = (EditText) findViewById(R.id.edtLogPassword);

        btnLogin = (Button) findViewById(R.id.btnLogin);

  

        /* Login button click event */

        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

  

                /* Getting user entered values from edittext */

                String userName = "", userPassword = "";

                userName = edtLogUsername.getText().toString();

                userPassword = edtLogPassword.getText().toString();

  

                if (userName.toLowerCase().equals("admin") == true && userPassword.toLowerCase().equals("admin") == true) {

  

                    /* Initialize object of SharedPreferences and storing data */

                    sharedPreferences = getSharedPreferences(PreferencesName, Context.MODE_PRIVATE);

                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    editor.putString("Username", userName);

                    editor.commit();

  

                    Intent i = new Intent(MainActivity.this, Home.class);

                    startActivity(i);

                }

            }

        });

    }

}

You can use any number of putString() with editor to store data.

Retrieving and Removing data from Shared Preference

Step 1. Create new activity with name Home to retrieve Username store in Shared Preference. Design screen according to your requirement. My code is given below. I have used TextView to show Username and Logout button to logout from application by removing data from Shared Preference.

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:gravity="center_horizontal"

    android:orientation="vertical"

    android:padding="15dp"

    tools:context=".Home">

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="15dp"

        android:text="Welcome To My App"

        android:textSize="20dp"

        android:textStyle="bold" />

  

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="40dp"

        android:orientation="horizontal">

  

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginBottom="5dp"

            android:text="Username : "

            android:textSize="16dp" />

  

        <TextView

            android:id="@+id/txtHomeUsername"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginBottom="5dp"

            android:text=""

            android:textSize="16dp"

            android:textStyle="bold" />

  

    </LinearLayout>

  

    <Button

        android:id="@+id/btnLogout"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Logout" />

  

</LinearLayout>

Home.java

package com.example.sharedpreferenceexample;

  

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

  

public class Home extends AppCompatActivity {

  

    /* Declare object to store controls of activity_main.xml file */

    TextView txtHomeUsername;

    Button btnLogout;

  

    /* Final variables */

    public static final String PreferencesName = "AppPref";

  

    /* Declare object of SharedPreferences */

    SharedPreferences sharedPreferences;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

  

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);

  

        /* Find controls from activity_main.xml file and initialize it to object */

        txtHomeUsername = (TextView) findViewById(R.id.txtHomeUsername);

        btnLogout = (Button) findViewById(R.id.btnLogout);

  

        /* Retrieving values from Shared Preference */

        sharedPreferences = getSharedPreferences(PreferencesName, Context.MODE_PRIVATE);

        if (sharedPreferences != null) {

            String userName = sharedPreferences.getString("Username", null);

            txtHomeUsername.setText(userName);

  

        } else {

            /* If Shared Preference is null than it will redirect to Login activity */

            Intent i = new Intent(Home.this, MainActivity.class);

            startActivity(i);

        }

  

        /* Logout button click event */

        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

  

                /* Removing all values from Shared Preference */

                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.clear();

                editor.commit();

  

                Intent i = new Intent(Home.this, MainActivity.class);

                startActivity(i);

            }

        });

    }

}

Storing and Retrieving data of other data types

  • To store data of other datatypes such as you can use following code.

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("Username", userName);

editor.putBoolean("KeyName", true);

editor.putInt("KeyName", 1);

editor.putFloat("KeyName", Float.parseFloat("1.2"));

editor.putLong("KeyName", Long.parseLong("9876543210"));

editor.commit();

  • To retrieve data of other data types use respective syntax according to its data type.

SharedPreferences sharedPreferences = getSharedPreferences(PreferencesName, Context.MODE_PRIVATE);

String userName = sharedPreferences.getString("Username", null);

Boolean boolVal = sharedPreferences.getBoolean("KeyName", false);

Integer intVal = sharedPreferences.getInt("KeyName", -1);

Float floatVal = sharedPreferences.getFloat("KeyName", Float.parseFloat("0.0"));

Long longVal = sharedPreferences.getLong("KeyName", Long.parseLong("9876543210"));

You can change KeyName as per your requirement to store data. KeyName must be same for storing and retrieving data.

Parameters in getSharedPreferences()

In getSharedPreferences() method first parameter is Key, which will be unique and is used to identify each data uniquely stored in Shared Preference. Second parameter is MODE. Total 6 modes are available.

  • Context.MODE_PRIVATE: By using this mode, data can only be accessed by the calling application.
  • Context.MODE_APPEND: This mode is used to append new preference in already existing preference.
  • Context.MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default.
  • Context.MODE_MULTI_PROCESS: This mode will check modification of shared preference even if instance of SharedPreference has been loaded.
  • Context.MODE_WORLD_WRITEABLE: If you use this mode, it will allow other application to write preference.
  • Context.MODE_WORLD_READABLE: If you use this mode, it will allow other application to read preference.

Methods used with SharedPreference Editor

Here are some methods used with Shared Preference Editor to Save and Clear data from it.

  • editor.commit(): This method is used to save changes to Shared Preference. It returns true if work saved or false if not saved.
  • editor.apply(): This method is also used to save changes to Shared Preference but it does not return anything.
  • editor.clear(): This method will remove all values from Shared Preference.
  • editor.remove("KeyName"): This method will remove value of key passed as a parameter.

Your Project Structure may look like,

Now run this application in AVD or in your mobile and check the application. The output screen shown below.

I hope you like this blog. If you have any query, please comment below. Thank You… :)