Android SharedPreferences to save data internally Tutorial

In this tutorial, we will learn how to use Sharedpreferences to store data internally in an Android Application.

 

Introduction

Android provides many ways to store the data internally in an Android Application. One of the way is SharedPreferences. SharedPreferences allow you to store data using Key value pair.

In this tutorial, we explain how to store the data list internally using SharedPreferences.

 




Create SharedPreference

To store data using SharedPreference, we need to call the getSharedPreferences() method that returns a SharedPreference instance pointing to the file that contains the values of preferences. The first parameter is the key and the second parameter is MODE as shown below:

 

public class MainActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedPrefs;
    SharedPreferences.Editor editor;

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

        sharedPrefs = getSharedPreferences(MainActivity.MyPREFERENCES, 
                               Context.MODE_PRIVATE);
        editor = sharedPrefs.edit();
    }
}

 

Save object to sharedpreferences

To save the data in sharedpreferences by using SharedPreferences.Editor class. We need to call edit method of the shared preference.

editor = sharedPrefs.edit();
editor.putString("key", "value");
editor.commit();

 

Get data from sharedpreference

To get the data for corresponding keys from sharedpreference, we need to call the sharedpreferences.getString() method as shown below:

if (sharedPrefs.contains("key")) {

      sharedPrefs.getString("key", null);
}

 

Remove the Data from sharedpreferences

To remove the data for corresponding keys from sharedpreferences, we need to call the remove() method of Editor class as shown below:

 editor.remove("key");
 editor.commit();

 

Create a New Project

We learn how to save list of data in the sharedPrefrences. Now, Create a new project in android studio.

Creating Layout

We will create three method to save and remove data at certain position in the saved list and remove all data in sharedPreferences. All methods will perform on clicking the button. So, we need to use the Button widget.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="app.num.sharedprefrences.MainActivity">

   <Button
       android:id="@+id/saved"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Add in SharedPrefrences"
       android:onClick="addListInSharedPrefrences"/>

    <Button
        android:id="@+id/remove"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Remove from SharedPrefrences"
        android:onClick="setRemoveSharedPrefrences"
        android:layout_below="@+id/saved"/>

    <Button
        android:id="@+id/complete_remove"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Complete Remove SharedPrefrences"
        android:onClick="completlyRemove"
        android:layout_below="@+id/remove"/>
</RelativeLayout>

 

sharedprefrences
 

Saved Data list in SharedPreferences

We will add data in SharedPreferences in the json form for that we will create a JsonObject and add it into sharedPreferernces.

First, we will check key value pair exist or not in the sharefPrefrences. If key value pair is missing then we will add jsonObject into JsonArray to save in sharedPreferences. If key value pair already exist then add jsonObject into the list and save in the sharedPreferences.

public class MainActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedPrefs;
    SharedPreferences.Editor editor;
    int num =1;

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

        sharedPrefs = getSharedPreferences(MainActivity.MyPREFERENCES, 
                                           Context.MODE_PRIVATE);
        editor = sharedPrefs.edit();
    }

    public void addListInSharedPrefrences(View view){

        //create json object
        JSONObject jsonObject = new JSONObject();
        try {
            // add the data into jsonObject
            jsonObject.put("id", num);
            jsonObject.put("name","SharedPrefrences"+num);

        } catch (Exception e) {

            e.printStackTrace();
        }
        // check key(list) exist into sharedPreferences
        if (sharedPrefs.contains("list")) {
           /**
            * key exist in the sharedPreferences. 
            * get the data from the key (list) and new data into list .
            */
            String storedCarList = sharedPrefs.getString("list", null);
            try {

                JSONArray jsonArray = new JSONArray(storedCarList);
                jsonArray.put(jsonObject);
                editor.putString("list", jsonArray.toString());
                editor.commit();

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            // key is not exist in the sharedPreferences.
            JSONArray jsonArrays = new JSONArray();
            jsonArrays.put(jsonObject);
            editor.putString("list", jsonArrays.toString());
            editor.commit();
        }

        Toast.makeText(getApplicationContext(), "Saved: " + 
                       sharedPrefs.getString("list",null),
                       Toast.LENGTH_SHORT).show();

        num = num +1;
    }
}

 

Remove the data at certain Position in the stored list

If you want to remove the data at certain position of list then get the data and pass it into a new JsonArray and remove that position in list. And save in sharedPreferences.

public class MainActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedPrefs;
    SharedPreferences.Editor editor;
    int num =1;

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

        sharedPrefs = getSharedPreferences(MainActivity.MyPREFERENCES, 
                                          Context.MODE_PRIVATE);
        editor = sharedPrefs.edit();
    }

    public void addListInSharedPrefrences(View view){

        //create json object
        JSONObject jsonObject = new JSONObject();
        try {
            // add the data into jsonObject
            jsonObject.put("id", num);
            jsonObject.put("name","SharedPrefrences"+num);

        } catch (Exception e) {

            e.printStackTrace();
        }
        // check key(list) exist into sharedPreferences
        if (sharedPrefs.contains("list")) {
           /**
            * key exist in the sharedPreferences. 
            * get the data from the key (list) and new data into list .
            */
            String storedCarList = sharedPrefs.getString("list", null);
            try {

                JSONArray jsonArray = new JSONArray(storedCarList);
                jsonArray.put(jsonObject);
                editor.putString("list", jsonArray.toString());
                editor.commit();

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            // key is not exist in the sharedPreferences.
            JSONArray jsonArrays = new JSONArray();
            jsonArrays.put(jsonObject);
            editor.putString("list", jsonArrays.toString());
            editor.commit();
        }

        Toast.makeText(getApplicationContext(), "Saved: " +
                      sharedPrefs.getString("list",null),
                      Toast.LENGTH_SHORT).show();

        num = num +1;
    }
    // Remove the data at certain position
    public void setRemoveSharedPrefrences(View view){
        // get the data from sharedPreferences
        String storedString = sharedPrefs.getString("list", null);
        //create new jsonArray
        JSONArray NewArray = new JSONArray();

        try {
            
            JSONArray array = new JSONArray(storedString);
            for (int j = 0; j < array.length(); j++) {

                JSONObject jsonObject = array.getJSONObject(j);
                // Remove the Data whose id is 2.
                if (!jsonObject.getString("id").equals("2")) {
                    NewArray.put(array.get(j));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (NewArray.length() == 0) {
            //there is no list rest after 
           //removing some data then removethe key  
            editor.remove("list");
            editor.commit();
        } else {
            // After removing the data and save rest of list of data.
            editor.putString("list", NewArray.toString());
            editor.commit();
        }

        Toast.makeText(getApplicationContext(), "Final saved: " + sharedPrefs.getString("list",null),
                Toast.LENGTH_SHORT).show();

    }
}

 

Remove the key in the sharedPreferences

We can remove the data of corresponding key by using remove() method.

public class MainActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedPrefs;
    SharedPreferences.Editor editor;
    int num =1;

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

        sharedPrefs = getSharedPreferences(MainActivity.MyPREFERENCES, 
                                           Context.MODE_PRIVATE);
        editor = sharedPrefs.edit();
    }

    public void addListInSharedPrefrences(View view){

        //create json object
        JSONObject jsonObject = new JSONObject();
        try {
            // add the data into jsonObject
            jsonObject.put("id", num);
            jsonObject.put("name","SharedPrefrences"+num);

        } catch (Exception e) {

            e.printStackTrace();
        }
        // check key(list) exist into sharedPreferences
        if (sharedPrefs.contains("list")) {
           /**
            * key exist in the sharedPreferences. 
            * get the data from the key (list) and new data into list .
            */
            String storedCarList = sharedPrefs.getString("list", null);
            try {

                JSONArray jsonArray = new JSONArray(storedCarList);
                jsonArray.put(jsonObject);
                editor.putString("list", jsonArray.toString());
                editor.commit();

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            // key is not exist in the sharedPreferences.
            JSONArray jsonArrays = new JSONArray();
            jsonArrays.put(jsonObject);
            editor.putString("list", jsonArrays.toString());
            editor.commit();
        }

        Toast.makeText(getApplicationContext(), "Saved: "
                + sharedPrefs.getString("list",null),
                Toast.LENGTH_SHORT).show();

        num = num +1;
    }
    // Remove the data at certain position
    public void setRemoveSharedPrefrences(View view){
        // get the data from sharedPreferences
        String storedString = sharedPrefs.getString("list", null);
        //create new jsonArray
        JSONArray NewArray = new JSONArray();

        try {
            
            JSONArray array = new JSONArray(storedString);
            for (int j = 0; j < array.length(); j++) {

                JSONObject jsonObject = array.getJSONObject(j);
                // Remove the Data whose id is 2.
                if (!jsonObject.getString("id").equals("2")) {
                    NewArray.put(array.get(j));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (NewArray.length() == 0) {
            //there is no list rest after removing some data then removethe key  
            editor.remove("list");
            editor.commit();
        } else {
            // After removing the data and save rest of list of data.
            editor.putString("list", NewArray.toString());
            editor.commit();
        }

        Toast.makeText(getApplicationContext(), "Final saved: " + sharedPrefs.getString("list",null),
                Toast.LENGTH_SHORT).show();

    }

    public void completlyRemove(View view){

        editor.remove("list");
        editor.commit();
    }
}

 

 

 


The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com