Shared Preference in Android

Introduction

This article explains what a Shared Preference in Android is. A Shared Preference stores a value and retrieves a key, value pair of data.

Before proceeding to the tutorial I will explain the basics necessary for working with Shared Preferences.

We obtain an object of the Shared Preference class by calling the getSharedPrefrence(string name, int mode) method that takes a string value and an integer type value as parameters.

SharedPreferences pref = getSharedPreferences("MyPref", 0);

For private mode we can use the value 0.

After that we get an instance of the SharedPrefrence.Editor by which we call the edit() method to store the value that we want.

Editor editor = pref.edit();

Finalyy we call the commit method with the editor, as in:

editor.commit ();

We can store any primitive data type (int, float, long string, boolean ) using sharedpreference by calling the method with an editor object, as in:
 

editor.putBoolean("key_name", true); // Storing boolean - true/false

              editor.putString("key_name", "string value"); // Storing string

              editor.putInt("key_name", "int value"); // Storing integer

              editor.putFloat("key_name", "float value"); // Storing float

              editor.putLong("key_name", "long value"); // Storing long

          editor.commit();

Step 1

Create a new project as "File" -> "New" -> "Android Application project" as shown below.

 

Shared.jpg

Step 2

Now open the XML file  "res/layout/activity_main.xml" and update it as in the following code.
 

<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:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    tools:context=".MainActivity">

 

    <LinearLayout

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:id="@+id/linearlayout1"

          android:orientation="horizontal">

 

        <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="Store value"

                android:id="@+id/textViewNaame"/>

        <EditText

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:id="@+id/name"

                android:layout_marginLeft="50dp"/>

 

    </LinearLayout>

 

    <Button

            android:layout_width="100dp"

            android:layout_height="wrap_content"

            android:text="stored"

            android:id="@+id/button" android:layout_below="@+id/textViewretrive" android:layout_centerHorizontal="true"

            android:layout_marginTop="39dp"/>

    <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="retrievedata"

            android:id="@+id/textViewretrive"

 

            android:layout_marginTop="26dp" android:layout_below="@+id/linearlayout1"

            android:layout_alignLeft="@+id/linearlayout1"/>

    <Button

            android:layout_width="100dp"

            android:layout_height="wrap_content"

            android:text="retrieve"

            android:id="@+id/button2" android:layout_below="@+id/button" android:layout_alignLeft="@+id/button"

            android:layout_marginTop="42dp"/>

</RelativeLayout>

Step 3
 

package com.sharedprefrence;

 

import android.content.SharedPreferences;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Button;

import android.widget.Toast;

 

public class MainActivity extends Activity {

 

    EditText edttextname,edttextword;

    TextView txtviewname,txtviewword,txtviewretrieve;

    SharedPreferences settings;

    Button btnstore,btnretrieve;

    public static final String PREF="any_pref";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        edttextname=(EditText)findViewById(R.id.name);

        txtviewname=(TextView)findViewById(R.id.textViewNaame);

        btnstore=(Button)findViewById(R.id.button);

        txtviewretrieve=(TextView)findViewById(R.id.textViewretrive);

        btnretrieve=(Button)findViewById(R.id.button2);

 

    btnstore.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

 

            String name=edttextname.getText().toString();

            SharedPreferences store = getSharedPreferences(PREF, MODE_PRIVATE);

            SharedPreferences.Editor editor = store.edit();

            editor.putString("any_pref",name);

            editor.commit();

            Toast.makeText(getApplicationContext(),

                    "Store", Toast.LENGTH_LONG).show();

    }

    });

    btnretrieve.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            SharedPreferences store = getSharedPreferences(PREF, MODE_PRIVATE);

            String retrievestring = (store.getString("any_pref", ""));

            txtviewretrieve.setText(retrievestring);

            Toast.makeText(getApplicationContext(),

                    "Retrive", Toast.LENGTH_LONG).show();

        }

    });

}

}


Step 4

See the output:

image store.jpg

Step 5
 

image retrieve.jpg
 


 

Up Next
    Ebook Download
    View all
    Learn
    View all