How to save the object of the model class in Preferences

Malwinder Singh
AndroidPub

--

Hello,

In this article, I shall tell you about how to save the object of the model class (POJO) in preferences.

Many times, we need to save an instance of a class which has only fields like Int, Long, Float, Double, String, Boolean and has further objects of different classes which are again model classes.

In Android, SharedPreferences class can save only these:

We use the GSON library to convert the model class to JSON String and we save that JSON String into the SharedPreferences. We read back that JSON String and convert it back to the object when we want to read it.

To add GSON library, add following in our module level build.gradle:

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

The above line shall add the GSON library to the project.

Now we write a singleton class that contains the function to save the Object in SharedPreference and another method to read the object from SharedPreferences.

How to use the above methods?

First, we initialize ModelPreferencesManager in onCreate the function of our application class.

class MyApplication : Application{
override fun onCreate() {
super.onCreate()
ModelPreferencesManager.with(this)
//...
}
}

To use this, first, we create a class of our deliciousApple:

data class Apple(val size: Float, val weight: Float)

We create a bag for these apples:

data class Bag(var apple: List<Apple>)

Now, we create an object of Bag class:

val apples = listOf(Apple(5f, 50f),
Apple(6f, 55f),
Apple(7f, 60f),
Apple(8f, 65f))
val bag = Bag(apples)Now, we will save this object:ModelPreferencesManager.put(bag, "KEY_BAG")

To read it back, we use the following:

val bag = ModelPreferencesManager.get<Bag>("KEY_BAG")

Following String is stored in Shared Preferences:

{
"apple":[
{
"size":5.0,
"weight":50.0
},
{
"size":6.0,
"weight":55.0
},
{
"size":7.0,
"weight":60.0
},
{
"size":8.0,
"weight":65.0
}
]
}

Hope you liked this article!

Please support this blog by contributing here: https://www.patreon.com/malwinder πŸ₯°

Buy me a coffee πŸ₯°

If you have any questions, then please write down a response in the response section.
If you liked this article, then please press the πŸ‘ icon.
Thank you!
Peace! πŸ™‚

--

--

Malwinder Singh
AndroidPub

Flutter, Kotlin & Android. Worked on projects of Emerson and Omron, 50k+ views on this blog, 6k+ repo on StackOverflow, Drone startup linkedin.com/in/malwinder