How to use Shared Preferences to save more than one values
Android Sample Codes

How to use Shared Preferences to save more than one values

How to use Shared Preferences to save more than one values | in this tutorial, we will learn how to store and retrieve multiple values using Shared Preferences in android.

I have already discussed Storing and Retrieving data Using Shared Preferences tutorial for storing and retrieving single value using Shared Preference in android.

In this Android example, we will see How to use Shared Preferences to save more than one values under same key and retrieve values from it.

How to use Shared Preferences to save more than one values

In this tutorial we would going to store multiple values to Shared Preferences .

As you know the primary purpose of using Shared Preferences in android is to store user specific details. Suppose when a user logged into the android application, we can display the username of a person in each page or in each activity using Shared Preferences.

Sessions are useful when you want to store user specific data globally throughout the application when a user login to an application. This can be done by storing the data in android shared preferences.

Shared Preferences is used to stores private data in key-value pairs.

In Shared Preferences save data to shared preference by calling the getSharedPreferences() method.

The SharedPreferences Editor is used to apply the changes which we have made while storing the data. The data is saved using commit() method.

You can create a new shared preference file or you can accessing existing shared preference file by calling one of the following methods:

    • getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter.
SharedPreferences sp;
sp=getSharedPreferences("SD", Context.MODE_PRIVATE);
    • getPreferences() — Use this if you need to use only one shared preference file for the activity. The file that belongs to the activity, you don’t need to supply a name as above.
 SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Create a new project by go to File>New>New Project,select Empty Activity and give name to your android application.

I have created Save, Select, Delete , Update and Clear options for handling the values using shared preference in How to use Shared Preferences to save more than one values tutorial.

 Working of Each Button

 SAVE     : This is used to save the values.

SELECT  : It will retrieve name and age based on  user ID. Before proceed please provide user ID.

UPDATE : Once you retrieve using select button ,you can update values.

DELETE : First you have to retrieve the user details using SELECT button. Then you can delete the values using DELETE button.

CLEAR : You can clear all values in the text field using CLEAR Button.

The layout for creating user interface is shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:hint="Enter Your Id"
        android:padding="11dp"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:hint="Enter Your Name"
        android:padding="11dp"
        android:ems="10"
        android:inputType="textPersonName" />
    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:hint="Enter Your Age"
        android:padding="11dp"
        android:ems="10"
        android:inputType="textPersonName" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="SAVE" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="SELECT" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/button2"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="UPDATE" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/button3"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="DELETE" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/button3"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="CLEAR" />
    </LinearLayout>
</LinearLayout>

The graphical representation of above layout looks like

How to use SharedPreferences to save more than one values

The java code for handling values using shared preference is updated in the main activity file.

MainActivity.java

package com.example.sharedpreferencetostoremultiplevalues;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

   SharedPreferences Sprefs;
   EditText id;
   EditText name;
   EditText age;
   String Value;
   private String prefName = "report";

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

        id=(EditText) findViewById(R.id.editText1);
        name=(EditText) findViewById(R.id.editText2);
        age=(EditText) findViewById(R.id.editText3);
        Button save=(Button) findViewById(R.id.button1);
        Button select=(Button) findViewById(R.id.button2);
        Button update=(Button) findViewById(R.id.button3);
        Button delete=(Button) findViewById(R.id.button4);
        Button clear=(Button) findViewById(R.id.button5);


        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                Sprefs = getSharedPreferences(prefName, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = Sprefs.edit();

                if (id.getText().toString().equals("")||name.getText().toString().equals("")||age.getText().toString().equals("")){

                    Toast.makeText(getApplicationContext(), "Please Fill All the Fields",Toast.LENGTH_SHORT).show();
                }
                else if (!Sprefs.getString("id"+id.getText().toString(),"").toString().equals("")){
                    Toast.makeText(getBaseContext(), "User is already Registered",Toast.LENGTH_SHORT).show();
                }
                else {
                    //---save the values in the EditText view to preferences---
                    editor.putString("id"+id.getText().toString(),id.getText().toString());
                    editor.putString("name"+id.getText().toString(),name.getText().toString());
                    editor.putString("age"+id.getText().toString(),age.getText().toString());
                    editor.commit();//---saves the values---
                    Toast.makeText(getBaseContext(), "User Details Registered",Toast.LENGTH_SHORT).show();
                    id.setText("");
                    name.setText("");
                    age.setText("");

                }
            }
        });

       select.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                Sprefs = getSharedPreferences(prefName, Context.MODE_PRIVATE);
                //Value=Sprefs.getString("id"+id.getText().toString(),"");
                if(id.getText().toString().equals(""))
                {
                    Toast.makeText(getBaseContext(), "Please Enter User ID",Toast.LENGTH_SHORT).show();
                    id.setText("");
                    name.setText("");
                    age.setText("");

                }
                else if(Sprefs.getString("id"+id.getText().toString(),"").toString().equals("")){
                    Toast.makeText(getBaseContext(), "No such User ID Exits. Provide Valid User ID",Toast.LENGTH_SHORT).show();
                }
                else{
                    //name.setText(Sprefs.getString("name"+name.getText().toString(),"").toString());
                    //age.setText(Sprefs.getString("age"+age.getText().toString(),"").toString());
                    name.setText(Sprefs.getString("name"+id.getText().toString(),"").toString());
                    age.setText(Sprefs.getString("age"+id.getText().toString(),"").toString());

                }
                }
        });

        update.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                Sprefs = getSharedPreferences(prefName,Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = Sprefs.edit();

                //---save the values in the EditText view to preferences---

                if (id.getText().toString().equals("")||name.getText().toString().equals("")||age.getText().toString().equals("")){

                    Toast.makeText(getApplicationContext(), "Please Fill All the Fields",Toast.LENGTH_SHORT).show();
                }
                else if (Sprefs.getString("id"+id.getText().toString(),"").toString().equals("")){

                    Toast.makeText(getApplicationContext(), "Cannot Update: No Such User Exists",Toast.LENGTH_SHORT).show();
                }
                else {

                    //---save the values in the EditText view to preferences---
                    editor.putString("id"+id.getText().toString(),id.getText().toString());
                    editor.putString("name"+id.getText().toString(),name.getText().toString());
                    editor.putString("age"+id.getText().toString(),age.getText().toString());
                    editor.commit();//---saves the values---
                    Toast.makeText(getBaseContext(), "Updated Your Data Successfully",Toast.LENGTH_SHORT).show();
                    id.setText("");
                    name.setText("");
                    age.setText("");
                }

            }
        });

        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (id.getText().toString().equals("")||name.getText().toString().equals("")||age.getText().toString().equals("")){

                    Toast.makeText(getApplicationContext(), "Please Fill All the Fields",Toast.LENGTH_SHORT).show();
                }
                else if (Sprefs.getString("id"+id.getText().toString(),"").toString().equals("")){

                    Toast.makeText(getApplicationContext(), "Cannot Delete : No Such User ID Exists",Toast.LENGTH_SHORT).show();
                }
                else {
                    SharedPreferences.Editor ed=Sprefs.edit();
                    ed.clear();// remove all data
                    ed.commit();// save changes
                    Toast.makeText(getBaseContext(), "Deleted Your Data Record Successfully",Toast.LENGTH_SHORT).show();
                    id.setText("");
                    name.setText("");
                    age.setText("");
                }

            }
        });
        clear.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                id.setText("");
                name.setText("");
                age.setText("");
            }
        });

    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sharedpreferencetostoremultiplevalues">
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />

    <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>

 

Output of how to use Shared Preferences to save more than one values is shown below.

How to use SharedPreferences to save more than one values

 

 

Leave a Reply

Your email address will not be published.