Android Shared Preferences to Save and Read Data

Android Shared Preferences is a powerful and efficient way to store data of your application inside the phone’s local storage. The data that is stored will stay persistent inside your Android device unless you clear the app’s data or uninstall the app. So, killing the app will not clear the data, please keep this in mind.

The implementation of Shared Preferences on Android is very simple and easy. You only have to call the getSharedPreferences() method from the Android framework. Then you can choose to read the data via get method or save data via edit method. Or you can even clear the data programmatically using remove method.

What will the app look like?

The app will look like this after you finish this tutorial:

Android Shared Preferences to Save and Read Data final app

What will you learn?

  • Know how to read and save data using Android Shared Preferences.
  • Understand how to remove stored data programmatically.

Note: In this post, I used Android Studio 3.5.3, make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.61.

Getting Started – Android Shared Preferences to Save and Read Data

Open your Android Studio and choose to Start a new Android Studio Project. Then set the Application Name AndroidSharedPref and select Kotlin as the language. Give the Activity Name MainActivity and wait until the Android Studio finishes preparing your project.

Preparing the XML Layout

The first is preparing the XML layout for our app here. Open the activity_main.xml inside the res/layout directory and put the code below:

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

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Your Name"
       android:textSize="14sp"
       android:textStyle="bold"
       />

   <EditText
       android:id="@+id/etName"
       android:layout_width="match_parent"
       android:layout_height="50dp"
       android:hint="Enter your name"
       android:textSize="16sp"
       android:layout_marginTop="4dp"
       android:maxLength="100"
       android:paddingTop="4dp"
       android:paddingBottom="4dp"
       />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Your Age"
       android:textSize="14sp"
       android:textStyle="bold"
       android:layout_marginTop="12dp"
       />

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:layout_marginTop="4dp">

       <EditText
           android:id="@+id/etAge"
           android:layout_width="150dp"
           android:layout_height="50dp"
           android:hint="Enter your age"
           android:textSize="16sp"
           android:inputType="number"
           android:maxLength="3"
           android:paddingTop="4dp"
           android:paddingBottom="4dp"
           />

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="years old"
           android:textSize="14sp"
           android:layout_marginLeft="10dp"
           />

   </LinearLayout>

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Married"
       android:textSize="14sp"
       android:textStyle="bold"
       android:layout_marginTop="12dp"
       />

   <RadioGroup
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:layout_marginTop="4dp">

       <RadioButton
           android:id="@+id/rbYes"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Yes"
           android:checked="true"
           />

       <RadioButton
           android:id="@+id/rbNo"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="No"
           android:layout_marginLeft="12dp"
           />

   </RadioGroup>

   <Button
       android:id="@+id/btSaveData"
       android:layout_width="match_parent"
       android:layout_height="45dp"
       android:text="Save Data"
       android:background="@color/colorPrimary"
       android:textColor="#fff"
       android:layout_marginTop="20dp"
       />

   <Button
       android:id="@+id/btClearData"
       android:layout_width="match_parent"
       android:layout_height="45dp"
       android:text="Clear Data"
       android:background="#dedede"
       android:textColor="#000"
       android:layout_marginTop="20dp"
       />

</LinearLayout>

The layout will be as simple as that. It will only contain a form containing EditTexts for name and age, RadioButtons for marital status (yes or no), and two Buttons for saving data and clear data.

Read Data from Shared Preferences

Open the MainActivity.kt file and replace the code with this:

package com.thesimplycoder.androidsharedpref

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.edit
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

   private val PREF_NAME = "MyPreferences"

   private val NAME_KEY = "name"
   private val AGE_KEY = "age"
   private val MARRIED_KEY = "married"

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       // get or retrieve data
       getData()
   }

   private fun getData() {
       val sharedPref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

       // read or get the data from shared preferences
       val name = sharedPref.getString(NAME_KEY, "")
       val age = sharedPref.getInt(AGE_KEY, 0)
       val isMarried = sharedPref.getBoolean(MARRIED_KEY, false)

       // setting the data to EditText
       etName.setText(name)
       etAge.setText(age.toString())

       // check the if already married or not
       if (isMarried) {
           rbYes.isChecked = true
           rbNo.isChecked = false
       } else {
           rbYes.isChecked = false
           rbNo.isChecked = true
       }
   }
}

To read or retrieve the data from persistent storage, just simply use the getSharedPreferences() method like the code above, inside the getData() method. It requires the preference name and what mode you want to use. The sample above is using the MODE_PRIVATE which means the data can be accessed by the calling application only.

When reading the data, you can use get methods. The get method will differ by its data type, for example, you want to read a String data, it uses getString(keyName: String, defaultValue: String). For Integer data, it uses getInt(keyName: String, defaultValue: Int). The same goes for the other types like this:

When you run the app, it will load a blank or empty data because we still haven’t implemented the save data yet.

Save Data using Shared Preferences

Next, add a new saveData() method inside the MainActivity.kt file.

private fun saveData() {
   val sharedPref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

   val name = etName.text.toString()
   val age = etAge.text.toString().toInt()
   val isMarried = rbYes.isChecked

   sharedPref.edit {
       putString(NAME_KEY, name)
       putInt(AGE_KEY, age)
       putBoolean(MARRIED_KEY, isMarried)
   }

   Toast.makeText(this, "Data is saved", Toast.LENGTH_SHORT).show()
}

You need to use the put method to save the data. The put method will differ by its data type, for example, you want to read a String data, it uses putString(keyName: String, value: String). As for Integer data, it uses putInt(keyName: String, value: Int). For the other types are gonna be like this:

Next, add the listener for Button saveData inside the onCreate() method:

btSaveData.setOnClickListener {
   saveData()
}
Android Shared Preferences to Saving data

When you save the data and kill the app, the data is still saved on the Shared Preferences.

Clear Data from Shared Preferences

As for clearing data is as simple as the get and put method. Add this clearData() method inside your activity class:

private fun clearData() {
   val sharedPref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
   sharedPref.edit {
       remove(NAME_KEY)
       remove(AGE_KEY)
       remove(MARRIED_KEY)
   }

   Toast.makeText(this, "Data is cleared", Toast.LENGTH_SHORT).show()

   // refresh the data
   getData()
}

Use the remove(keyName: String) method to clear or remove the data from Shared Preferences. After removing the data, we call the getData() method again to refresh the data on our app.

Next, add the listener for Button clearData inside the onCreate() method:

btClearData.setOnClickListener {
   clearData()
}
Android Shared Preferences to removing / clear data

For more info about the Android Shared Preferences, you can take a look at it here.

Where to go next?

You can download this full code from the link below:

Download final code

Be sure to check my other cool posts here about:

I hope you like my post, comment and share it with love!

You may also like...

Join the discussion...

This site uses Akismet to reduce spam. Learn how your comment data is processed.