---
title: "Android Persistence with Shared Preferences"  
description: "Hi all here we are going to implement Android Persistence with Shared Preferences in Android"  
author: "Manoj Pandey"  
published: 2015-02-19  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1592/android-persistence-with-shared-preferences  
category: "android"  
tags: ["android"]  
reading_time: 5 minutes  

---

# Android Persistence with Shared Preferences

Previously, we learn about Android [Persistence](https://www.mindstick.com/interview/848/what-is-meant-by-persistence) with [Internal Storage](https://answers.mindstick.com/qa/51515/how-much-internal-storage-does-each-iphone-model-have-can-internal-storage-be-expanded-is-it-possible-to-add-external-storage-does-the-iphone-have-a-microsd-slot). Now we see how to use Android Persistence with Shared Preferences.\

Android provides many ways of storing data of an [application](https://www.mindstick.com/articles/12824/calculator-application-in-android). One of this way is called Shared Preferences. Shared Preferences allow you to save and [retrieve data](https://www.mindstick.com/forum/159649/how-to-retrieve-data-from-object-tables-on-oracle) 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](https://www.mindstick.com/forum/155658/testing-connection-to-cloud-sql-instance-with-a-mysql-client-from-vm-instance) pointing to the file that contains the values of preferences.

The SharedPreferences class provides a general [framework](https://yourviews.mindstick.com/view/81101/time-for-improvement-in-healthcare-facility-framework) that allows you to save and retrieve [persistent](https://www.mindstick.com/interview/22840/what-is-the-use-of-persistent-store-coordinator-in-core-data) 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](https://www.mindstick.com/articles/66/how-to-create-controls-at-run-time-in-csharp-dot-net) 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](https://www.mindstick.com/mindstickarticle/426a745b-f32c-449e-a601-30fd2582fd85/images/56f5f09a-6bcc-4723-ae54-bd047f1ee1a8.png) ![Android Persistence with Shared Preferences](https://www.mindstick.com/mindstickarticle/426a745b-f32c-449e-a601-30fd2582fd85/images/be8880d4-46b1-4262-b894-dbc6a94c18e6.png)

Exit your [activity](https://www.mindstick.com/forum/23119/how-to-save-activity-state-in-android) and reopen this application

![Android Persistence with Shared Preferences](https://www.mindstick.com/mindstickarticle/426a745b-f32c-449e-a601-30fd2582fd85/images/be8880d4-46b1-4262-b894-dbc6a94c18e6.png)

---

Original Source: https://www.mindstick.com/articles/1592/android-persistence-with-shared-preferences

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
