Hello folks! In this article we’ll learn about How to read and write SharedPreferences and their example. Shared preference is used to store light weight data in key/value pairs.

Android provides different ways of storing data of an application. Shared preferences is a light weight data storage option provided by Android. It allow us to store and retrieve small amounts of primitive data as key/value pairs in a file on the device. Shared preferences is mostly used to save preferences, i.e., user-specific data, like application settings, login sessions, etc. SharedPreferences have a relatively small collection of key-values that you’d like to save such as String, int, float, Boolean, long.

Android stores Shared Preferences data as XML file in shared_prefs folder under /data/data/com.package.name or DATA/data/{application package} directory. The shared preferences file is stored in the storage path /data/data/com.package.name/shared_prefs/package_name_preferences.xml .

The Android framework manages the shared preferences file itself. The file is accessible to all the components of our app, but it is not accessible to other apps. Shared preferences are the best example when we need to store a small amount data as simple key/value pairs.

Read and Store data to a shared preferences file

In order to use shared preferences, we have to create the instance of shared preference by calling one of these methods:

  • getSharedPreferences(String name,int mode) – getSharedPreferences() method is an application-level preferences takes two parameter the first parameter is the name of the SharedPreference file and the second parameter is the MODE of preference like MODE_PRIVATE, MODE_APPEND.
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
  • getPreferences(int mode) – getPreferences() method is an activity-specific preferences, it takes one parameter i.e. the MODE of preference. It doesn’t require name as it will be the only preference file for this activity.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

SharedPreferences Modes :

SharedPreferences have different modes, like-

ModeDescription
MODE_PRIVATEThis mode will make the shared preferences private to the application.
MODE_WORLD_READABLEAs the name suggest it is world readable, and it might be the reason for the security loop holes in your application. So you should use this mode with extra care.
MODE_WORLD_WRITEABLEAs the name suggest it is world writable, so it is even more dangerous then the world readable mode. So you should use this mode with extra care.
MODE_MULTI_PROCESSIt is deprecated from API 23, so we should not use it.
MODE_APPENDIf you don’t want to destroy your existing preferences you can use this mode to append the preferences with your existing one.

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)

Instantiate an instance of the SharedPreferences

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);

Write data to SharedPreference File

Create an instance of SharedPreferences.Editor to write to shared preference file by calling the edit() method of SharedPreferences object.

SharedPreferences.Editor editor = sharedPref.edit(); //Initializing the Editor
editor.putString("key_name","string value");
editor.putInt("key_name","int value");
editor.putBoolean("key_name",true);
editor.putFloat("key_name","float value");
editor.putLong("key_name","long value");
// Save the changes in SharedPreferences
editor.commit();

Read data from Shared Preferences

// If value for key_name not exist then return second param value - In this case null
sharedPref.getString("key_name",null);
sharedPref.getInt("key_name",0);
sharedPref.getFloat("key_name",0);
sharedPref.getBoolean("key_name",true);
sharedPref.getLong("key_name",0);

Deleting data from Shared Preferences

SharedPreferences.Editor editor = sharedPref.edit();
editor.remove("key_name");// will delete key key_name
// Save the changes in SharedPreferences
editor.commit();

Clearing data from Shared Preferences

SharedPreferences.Editor editor = pref.edit();
//Clear all data from SharedPreferences
editor.clear();
// Save the changes in SharedPreferences
editor.commit();

Example:

1. Create a new project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to implement shared preferences in android using android studio and name it Shared Preference.

2. Designing Layout

Now open res -> layout -> activity_main.xml  file and just implement the following xml code .

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:inputType="textPersonName|textCapWords"
        android:layout_marginHorizontal="15dp"
        android:layout_marginTop="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <EditText
        android:id="@+id/address"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Address"
        android:inputType="text"
        android:layout_marginTop="12dp"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/name"/>

    <EditText
        android:id="@+id/email"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:layout_marginTop="12dp"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/address"/>

    <EditText
        android:id="@+id/password"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"
        android:layout_marginTop="12dp"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/email"/>

    <Button
        android:id="@+id/saveBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Save"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/password"/>

    <Button
        android:id="@+id/viewBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="View"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/saveBtn"/>

    <Button
        android:id="@+id/clearBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Clear"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/viewBtn"/>

    <TextView
        android:id="@+id/value"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        app:layout_constraintLeft_toLeftOf="@id/name"
        app:layout_constraintRight_toRightOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/clearBtn" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Implement SharedPreference

Now open your SharedPreference.java and add following code –

package net.technxt.sharedpreference;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    /*instantiate an instance of the SharedPreferences*/
    SharedPreferences sharedPref;
    //Initializing the Editor
    SharedPreferences.Editor editor;
    EditText name;
    EditText address;
    EditText email;
    EditText password;
    Button save, view, clear;
    TextView value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Context context = getApplicationContext();
        sharedPref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);/*instantiate an instance of the SharedPreferences*/
        editor = sharedPref.edit();//Initializing the Editor

        name = findViewById(R.id.name);
        address = findViewById(R.id.address);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        save = findViewById(R.id.saveBtn);
        view = findViewById(R.id.viewBtn);
        clear = findViewById(R.id.clearBtn);
        value = findViewById(R.id.value);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearAllData();
            }
        });

    }

    private void clearAllData() {
        //Clear all data from SharedPreferences
        editor.clear();
        // Save the changes in SharedPreferences
        boolean status = editor.commit();
        if (status){
            Toast.makeText(this,"Data cleared successfully.",Toast.LENGTH_LONG).show();
        }
        //get data and Update the UI
        getData();
    }

    private void saveData() {
        // Check if editText is empty
        if (name.getText().toString().isEmpty()) {
            name.setError("Oops! No Name");
            name.requestFocus();
            return;
        }
        if (address.getText().toString().isEmpty()) {
            address.setError("Oops! No address");
            address.requestFocus();
            return;
        }
        if (email.getText().toString().isEmpty()) {
            email.setError("Oops! No email");
            email.requestFocus();
            return;
        }
        if (password.getText().toString().isEmpty()) {
            password.setError("Oops! No password");
            password.requestFocus();
            return;
        }

        editor.putString("name", name.getText().toString());
        editor.putString("address", address.getText().toString());
        editor.putString("email", email.getText().toString());
        editor.putString("pass", password.getText().toString());
        // Save the changes in SharedPreferences
        boolean status = editor.commit();
        if (status){
            Toast.makeText(this,"Data insert successfully.",Toast.LENGTH_LONG).show();
        }
    }

    private void getData() {
        String valueData = "";
        // If value for key_name not exist then return second param value - In this case null
        if (sharedPref.contains("name")) {
            valueData += sharedPref.getString("name", null) + "\n";
        }
        if (sharedPref.contains("address")){
            valueData += sharedPref.getString("address", null) + "\n";
        }
        if (sharedPref.contains("email")){
            valueData += sharedPref.getString("email", null) + "\n";
        }
        if (sharedPref.contains("pass")){
            valueData += sharedPref.getString("pass", null);
        }

        updateUI(valueData);
    }

    private void updateUI(String valueData) {
        value.setText(valueData);
    }

}

4. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.technxt.sharedpreference">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now the app is ready to test using android device or any Emulator . The value will be same even you restart the App, but clearing it’s data will clear SharedPrefs also.

You can download the project Shared Preferences from the below link.

Thank you 🙂

%d bloggers like this: