Android Shared Preferences

By Kunal Kapoor
17-05-2018
1061

f you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.


SharedPreferences should not be used for storing large amounts of dynamic data. As mentioned previous, they are only used to store key values and data sets. eg if you are making a simple gaming app, you might want to use SharedPreferences to store high score points of user.

For larger amounts of data, use the File api's to store files on the device storage.


A project overview:


Lets assume the following project with four UI elements. One Edittext (to store the required data) , one TextView (to display the stored data) , and two buttons for Show and Save action:

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ourcoaching.simplesharedpreference.MainActivity">

<TextView
android:id="@+id/textview"
android:layout_width="215dp"
android:layout_height="47dp"
android:text="Welcome"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.217"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.765" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Show"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.828"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.765" />

<EditText
android:id="@+id/editText"
android:layout_width="215dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.202" />

android.support.constraint.ConstraintLayout
>


We will now attempt to save the data in the EditText upon the Save Button press and will display the data in the Textview upon Show button press


Let's create the java code. First define certain objects in MainActivity.class

private Button SaveButton,ShowButton;
private TextView textView;
private EditText editText;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;

private final String Data_key="High score";

Instantiating variables:

textView=(TextView)findViewById(R.id.textview);
SaveButton=(Button)findViewById(R.id.button);
ShowButton=(Button)findViewById(R.id.button2);
editText=(EditText)findViewById(R.id.editText);


Define the OnClick listeners for buttons:

SaveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SaveData();
}
});

ShowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ShowData();
}
});


First lets code the SaveData() method:

Instantiate the sharedpreferences object 

sharedPreferences=getApplicationContext().getSharedPreferences(Data_key,Context.MODE_PRIVATE);

Here, the data_key is the variable to define the value being stored. For different kind of data to be stored/read, use a different unique key each time. The Context.MODE_PRIVATE defines that this particular data cannot be accessed by others apps and services on the device

Next, instatntiate the object editor and get read the String from the editText to be saved.

finally put the command editor.commit() to save the data.

String valuetoSave=editText.getText().toString();

editor = sharedPreferences.edit();
editor.putString(Data_key, valuetoSave);
editor.commit();


Read the saved Data

To read the saved data, we'll programm the ShowData() method.

Instantiate the sharedpreferences object. Then read the saved string like this

String read_data=sharedPreferences.getString(Data_key,"NO DATA");



Complete Java Code: MainActivity.java

package com.ourcoaching.simplesharedpreference;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private Button SaveButton,ShowButton;
private TextView textView;
private EditText editText;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;

private final String Data_key="High score";

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

textView=(TextView)findViewById(R.id.textview);
SaveButton=(Button)findViewById(R.id.button);
ShowButton=(Button)findViewById(R.id.button2);
editText=(EditText)findViewById(R.id.editText);

SaveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SaveData();
}
});

ShowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ShowData();
}
});
}

private void SaveData(){
sharedPreferences=getApplicationContext().getSharedPreferences(Data_key,Context.MODE_PRIVATE);

String valuetoSave=editText.getText().toString();

editor = sharedPreferences.edit();
editor.putString(Data_key, valuetoSave);
editor.commit();

}

private void ShowData(){

sharedPreferences=getApplication().getSharedPreferences(Data_key, Context.MODE_PRIVATE);
String read_data=sharedPreferences.getString(Data_key,"NO DATA");
textView.setText(read_data);
}
}



Download the code from GitHub




Related Tutorials