SharedPreferences in android tutorial

Hey Technoz, in this tutorial, we are going to learn about SharedPreferences in android. SharedPreferences is a light weight and easy data structure which stores the data in the key-value pair in android. It is perfect choice when we have to store small amount of data in device memory without any internet connection.

It starts with creating an object of SharedPreferences class. When we have to get contents from the SharedPreferences, we use getSharedPreferences() method with the following syntax:

getSharedPreferences(String PREFS_NAME, int mode)

The first parameter PREFS_NAME is a unique name of SharedPreference and second one is an operating mode. There are following types of operating modes:


  • MODE_PRIVATE : This mode allows the values of SharedPreferences to be accessed by only the calling function
  • MODE_APPEND : This mode 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
  • MODE_MULTI_PROCESS : This method will check for modification of preferences even if the sharedpreference instance has already been loaded
  • MODE_WORLD_READABLE : This mode allow other application to read the preferences
  • MODE_WORLD_WRITEABLE : This mode allow other application to write the preferences

We can save the values in SharedPreferences by using the Editor class. We have to call edit() method on object of SharedPreference and it receives in an Editor object. See the syntax below:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key", "value");
editor.apply();

There are some more methods that we can assign to the editor. Which are:


  • apply() : It saves the changes made in SharedPreferences and works in the background
  • commit() : It is same as apply(), but it writes data to persistent storage immediately
  • clear() : It removes all the key-value pairs from the editor
  • remove(String key) : It will remove the value whose key has been passed as a parameter
  • putLong(String key, long value) : It will save a long value in a preference editor
  • putInt(String key, int value) : It will save a integer value in a preference editor
  • putFloat(String key, float value) : It will save a float value in a preference editor

Step by step tutorial

SharedPreferences in android example

So, lets start to build a new project step by step. Create a new project and write the following code in your xml file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    android:id="@+id/con">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="10sp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Technopoints"
                android:gravity="center_horizontal"
                android:textSize="30sp"
                android:textColor="@color/colorAccent"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="SharedPreferences Tutorial"
                android:gravity="center_horizontal"
                android:textSize="25sp"
                android:paddingBottom="5sp"
                android:textColor="@color/colorPrimaryDark"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="1sp"
                android:background="#000000" />
            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"
                android:inputType="textPersonName"/>
            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="email"
                android:inputType="textEmailAddress"/>
            <EditText
                android:id="@+id/message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Message"
                android:inputType="text" />
            <Button
                android:id="@+id/savebtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Save"/>
            <Button
                android:id="@+id/retbtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Retrieve"/>
            <Button
                android:id="@+id/clrbtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Clear"/>
            <Button
                android:id="@+id/delbtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Delete"/>
        </LinearLayout>
    </ScrollView>

</android.support.constraint.ConstraintLayout>

The above file provides the UI designing. We have created 3 EditText fields as name, email and message and 4 buttons preceding it. However, the layout will not perform any work for now. So, lets add the back end code.

Similarly, paste the following code in your java file.

package net.softglobe.tutorials;

import android.content.Context;
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;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText ed_name,ed_email,ed_message;
    Button save,retrieve,clr,delete;

    public static final String preferences = "myPreference";
    public static final String name = "nameKey";
    public static final String email = "emailKey";
    public static final String message = "msgKey";

    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //TextView initialization
        ed_name = findViewById(R.id.name);
        ed_email = findViewById(R.id.email);
        ed_message = findViewById(R.id.message);

        sharedPreferences = getSharedPreferences(preferences, Context.MODE_PRIVATE);

        //Buttons initialization
        save = findViewById(R.id.savebtn);
        retrieve = findViewById(R.id.retbtn);
        clr = findViewById(R.id.clrbtn);
        delete = findViewById(R.id.delbtn);

        //Save Button
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nm = ed_name.getText().toString();
                String ml = ed_email.getText().toString();
                String msg = ed_message.getText().toString();

                if (nm.isEmpty() || ml.isEmpty() || msg.isEmpty()){
                    Toast.makeText(MainActivity.this, "Please fill all the fields!", Toast.LENGTH_SHORT).show();
                }
                else {
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(name, nm); //Getting Name
                    editor.putString(email, ml); //Getting Email
                    editor.putString(message, msg); //Getting Message
                    editor.apply();
                    Toast.makeText(MainActivity.this, "Saved Successfully!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //Retrieve Button
        retrieve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharedPreferences = getSharedPreferences(preferences,MODE_PRIVATE);
                if (sharedPreferences.contains(name) && sharedPreferences.contains(email) && sharedPreferences.contains(message)){
                    ed_name.setText(sharedPreferences.getString(name,""));
                    ed_email.setText(sharedPreferences.getString(email,""));
                    ed_message.setText(sharedPreferences.getString(message,""));
                }
                else{
                    Toast.makeText(MainActivity.this, "No data available...", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //Clear Button
        clr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ed_name.setText("");
                ed_email.setText("");
                ed_message.setText("");
            }
        });

        //Delete Button
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ed_name.setText("");
                ed_email.setText("");
                ed_message.setText("");
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.clear(); //remove all values
                editor.apply(); //save changes
                Toast.makeText(MainActivity.this, "All data deleted Successfully!", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

We create an object sharedPreferences and define the Strings (name, email and message) as keys. We are opening the SharedPreferences in Private Mode. So, only this application can access it’s data.

We are taking the values entered by the user and saving them in the global strings, and also in the editor object. Even more, we call the apply() method on editor object to save the changes.

While retrieving, we call the method getString(), as we have all the values as strings. While in case of deleting, we call a method clear() to remove all the key value pairs. As a result, all data will be deleted. However, don’t forget to save the changes by using apply() method.

Now, lets see the working of app in the screenshots below.

SharedPreferences in android tutorial
Data saved in SharedPreferences

 

SharedPreferences in android tutorial
Data deleted from SharedPreferences

The data in SharedPreferences in android is stored in a xml file in the device on path: data=>data=><app-package-name>=>shared_prefs=><file-name>.xml Where, file-name will be the name of your SharedPreference key name.

Thus, we have seen how to use the SharedPreferences in android. If you have any doubts about this tutorial, feel free to comment below. Please subscribe us to stay updated and catch such knowledgeable tutorials.

Download Source Code

If you like to directly jump on the implementation, you can download the source code from below link.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.