articles

Home / DeveloperSection / Articles / Android Persistence with Shared Preferences

Android Persistence with Shared Preferences

Manoj Pandey 2971 19-Feb-2015

Previously, we learn about Android Persistence with Internal Storage. Now we see how to use Android Persistence with Shared Preferences.

Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key, value pair.

In order to use shared preferences, you have to call a method getSharedPreferences () that returns a SharedPreference instance pointing to the file that contains the values of preferences.

The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.  

1.      Create an android project.

2.      Add controls in activity_main.xml

<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:orientation="vertical"
    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=".MainActivity" >

    <LinearLayout
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_marginTop="30sp"
          android:orientation="horizontal" >

        <TextView
              android:id="@+id/tvName"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight=".40"
              android:text="Employee Name-: " />

        <EditText
              android:id="@+id/editName"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight=".60"
              android:maxLength="20" />
    </LinearLayout>

    <LinearLayout
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_marginTop="30sp"
          android:orientation="horizontal" >

        <TextView
              android:id="@+id/tvSallary"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight=".40"
              android:text="Sallary-: " />

        <EditText
              android:id="@+id/editSallary"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight=".60"
              android:digits="1234567890-."
              android:inputType="number"
              android:maxLength="15" />
    </LinearLayout>

    <LinearLayout
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:layout_marginTop="30sp"
          android:gravity="center" >

        <Button
              android:id="@+id/btnSave"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text=" Save " />
    </LinearLayout>

    <Button
          android:id="@+id/btnGetData"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:layout_marginTop="10sp"
          android:text="Retrieve Data" />

</LinearLayout>

 3.      And paste following code in MainActivity.class 

package com.example.androidpersistencesample;

 

import android.os.Bundle;

import android.app.Activity;

import android.content.Context;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

public class MainActivity extends Activity {

            Button btnSave, btnGetData;

            EditText etname;

            EditText etSallary;

 

// Define key Name

            public static final String MyPREFERENCES = "Employee";

            public static final String EName = "EmployeeName";

            public static final String ESallary = "EmployeeSallary";

 

            // Shared Preferences allow you to save and retrieve data in the form of

            // key,value pair.

            SharedPreferences sharedpreferences;

 

            @Override

            protected void onCreate(Bundle savedInstanceState) {

                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_main);

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

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

                        etname = (EditText) findViewById(R.id.editName);

                        etSallary = (EditText) findViewById(R.id.editSallary);

 

                        // This method retrieve data from file and fill value in edit text

                        readDatafromFile();

 

                        btnSave.setOnClickListener(new OnClickListener() {

 

                                    @Override

                                    public void onClick(View v) {

 

                                                // Interface used for modifying values in a SharedPreferences

                                                Editor editor = sharedpreferences.edit();

 

                                                // put key and value in Editor

                                                editor.putString(EName, etname.getText().toString());

                                                editor.putString(ESallary, etSallary.getText().toString());

 

                                                // after add data clear edittext

                                                etname.setText("");

                                                etSallary.setText("");

 

                                                // Commit your preferences changes back from this Editor to the

                                                // SharedPreferences object it is editing.

                                                editor.commit();

 

                                                Toast.makeText(getApplicationContext(), "Data saved",

                                                                        Toast.LENGTH_SHORT).show();

                                    }

                        });

                        btnGetData.setOnClickListener(new OnClickListener() {

 

                                    @Override

                                    public void onClick(View v) {

 

                                                readDatafromFile();

                                    }

                        });

            }

 

            public void readDatafromFile() {

 

                        // getSharedPreferences use if you need multiple preferences files

                        // identified by name, which you specify with the first parameter.

                        sharedpreferences = getSharedPreferences(MyPREFERENCES,

                                                Context.MODE_PRIVATE);

 

                        // set value in edit text

                        if (sharedpreferences.contains(EName)) {

 

                                    etname.setText(sharedpreferences.getString(EName, ""));

 

                        }

                        if (sharedpreferences.contains(ESallary)) {

                                    etSallary.setText(sharedpreferences.getString(ESallary, ""));

 

                        }

            }

}

 

And run your application

    Android Persistence with Shared Preferences      Android Persistence with Shared Preferences

 

Exit your activity and reopen this application

 

Android Persistence with Shared Preferences


Updated 07-Sep-2019

Leave Comment

Comments

Liked By