How to Save And Retrieve Class Object From Shared Preferences Using Gson Library in Kotlin

In this article, we will learn how to Save And Retrieve Class Object From Shared Preferences Using Gson Library in Kotlin. Many times, we need to save an instance of a class that has only fields like IntLongFloatDoubleStringBoolean and objects of different classes.

We use the GSON library that helps us to convert the model class to JSON String and then save the JSON String into the SharedPreferences. We read that JSON String and convert it back to the object whenever you want to read it.

Dependency GSON Library

To add the GSON library, add the following dependency in your module-level build.gradle. The below line adds the GSON library to your project.

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
  //Other dependencies of our project
}

To keep the example simple, let’s add just four properties to our MyObject class

class User {
    var myValue = 0
    var myAge: String? = null
    var myFirstName: String? = null
    var myLastName: String? = null
}

Simple Method to Store Class Object into Shared Preferences

val prefsEditor = appSharedPrefs.edit()
val gson = Gson()
val json = gson.toJson(obj)
prefsEditor.putString("MyObject", json)
prefsEditor.commit()
Output Screen of Shared Preferences Using Gson Library

Add two buttons and four EditText fields in the XML file. Add the onClick command to the XML so when the button is pressed our methods are executed.

Store Class Object in the SharedPreferences Using GSON

In the MainActivity add the following method. This method will be called when you click on the Save button. It will create an instance of “MyObject” and set the “MyValue” string to whatever you type in the EditText inputEditText. Then it will convert the object to a string using the GSON library and store that string in the SharedPreferences.

fun storeButton_Clicked(v: View?) {
        val inputFirstName =
            findViewById<View>(R.id.inputFirstName) as EditText
        val inputLastName =
            findViewById<View>(R.id.inputLastName) as EditText
        val inputAge =
            findViewById<View>(R.id.inputAge) as EditText
        val obj = MyObject()
        obj.myValue = 2
        obj.myFirstName = inputFirstName.text.toString()
        obj.myLastName = inputLastName.text.toString()
        obj.myAge = inputAge.text.toString()
        val appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.applicationContext)
        val prefsEditor = appSharedPrefs.edit()
        val gson = Gson()
        val json = gson.toJson(obj)
        prefsEditor.putString("MyObject", json)
        prefsEditor.commit()
        Toast.makeText(this, "Object stored in SharedPreferences", Toast.LENGTH_LONG)
    }

Get The Object From Shared Preferences

Now get the object from shared preferences and display it in the outputEditText. 

fun getButton_Clicked(v: View?) {
        val outputEditText =
            findViewById<View>(R.id.outputEditText) as TextView
        val appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.applicationContext)
        val gson = Gson()
        val json = appSharedPrefs.getString("MyObject", "")
        val obj = gson.fromJson(json, MyObject::class.java)
        outputEditText.setText("obj.MyFirstName: [" + obj.myFirstName + "] obj.MyLastName: [" + obj.myLastName + "] obj.myAge: [" + obj.myAge + "] obj.MyValue: [" + obj.myValue + "]")

        Toast.makeText(this, "Object fetch from SharedPreferences successfully", Toast.LENGTH_LONG)
    }

XML Code

<androidx.constraintlayout.widget.ConstraintLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#FFFFFF"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textDiplay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="24dp"
        android:hint="Enter Name"
        android:text="Store and Get an Object in Android Shared Preferences using GSON"
        android:textAlignment="center"
        android:textSize="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </TextView>

    <EditText
        android:id="@+id/inputFirstName"
        android:layout_width="353dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textDiplay"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="36dp"
        android:hint="First Name"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textDiplay">

    </EditText>

    <EditText
        android:id="@+id/inputLastName"
        android:layout_width="351dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inputFirstName"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="24dp"
        android:hint="Last Name"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputFirstName">

    </EditText>

    <EditText
        android:id="@+id/inputAge"
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inputLastName"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="28dp"
        android:hint="Age"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.54"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputLastName">

    </EditText>

    <Button
        android:id="@+id/storeButton"
        android:layout_width="222dp"
        android:layout_height="52dp"
        android:layout_below="@+id/inputAge"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="20dp"
        android:background="@color/design_default_color_primary"
        android:onClick="storeButton_Clicked"
        android:text="Save"
        android:textColor="@color/white"
        android:textSize="17dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputAge">

    </Button>

    <TextView
        android:id="@+id/outputEditText"
        android:layout_width="344dp"
        android:layout_height="53dp"
        android:layout_above="@+id/getButton"
        android:layout_below="@+id/storeButton"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="32dp"
        android:hint="Get Data show here"
        android:text=""
        android:textSize="15dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.492"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/storeButton">

    </TextView>

    <Button
        android:id="@+id/getButton"
        android:layout_width="218dp"
        android:layout_height="54dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:background="@color/design_default_color_primary"
        android:onClick="getButton_Clicked"
        android:text="Get"
        android:textColor="@color/white"
        android:textSize="17dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/outputEditText"
        app:layout_constraintStart_toStartOf="@+id/outputEditText"
        app:layout_constraintTop_toBottomOf="@+id/outputEditText"
        app:layout_constraintVertical_bias="0.47">

    </Button>

</androidx.constraintlayout.widget.ConstraintLayout>

MyObject Class

package com.example.handyopinion_sharedpreferences_gson

class MyObject {
    var myValue = 0
    var myAge: String? = null
    var myFirstName: String? = null
    var myLastName: String? = null
}

Main Activity Class

package com.example.handyopinion_sharedpreferences_gson

import android.app.Activity
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.gson.Gson
import java.util.function.IntFunction


class MainActivity : Activity() {
    /** Called when the activity is first created.  */
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun storeButton_Clicked(v: View?) {
        val inputFirstName =
            findViewById<View>(R.id.inputFirstName) as EditText
        val inputLastName =
            findViewById<View>(R.id.inputLastName) as EditText
        val inputAge =
            findViewById<View>(R.id.inputAge) as EditText
        val obj = MyObject()
        obj.myValue = 2
        obj.myFirstName = inputFirstName.text.toString()
        obj.myLastName = inputLastName.text.toString()
        obj.myAge = inputAge.text.toString()
        val appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.applicationContext)
        val prefsEditor = appSharedPrefs.edit()
        val gson = Gson()
        val json = gson.toJson(obj)
        prefsEditor.putString("MyObject", json)
        prefsEditor.commit()
        Toast.makeText(this, "Object stored in SharedPreferences", Toast.LENGTH_LONG)
    }

    fun getButton_Clicked(v: View?) {
        val outputEditText =
            findViewById<View>(R.id.outputEditText) as TextView
        val appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.applicationContext)
        val gson = Gson()
        val json = appSharedPrefs.getString("MyObject", "")
        val obj = gson.fromJson(json, MyObject::class.java)
        outputEditText.setText("obj.MyFirstName: [" + obj.myFirstName + "] obj.MyLastName: [" + obj.myLastName + "] obj.myAge: [" + obj.myAge + "] obj.MyValue: [" + obj.myValue + "]")

        Toast.makeText(this, "Object fetch from SharedPreferences successfully", Toast.LENGTH_LONG)
    }
}

Run the program. Save an object and retrieve it from SharedPreferences. That’s it. This is how to Save And Retrieve Class Object From Shared Preferences Using Gson Library in Kotlin.

If you have any questions or suggestions, feel free to ask in the comments section below.

Next Article

How to Save And Get Data From Shared Preferences in Kotlin

Please share this post:
Posts created 41

Ask a Question

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: