Search code examples
androidsharedpreferenceskotlinpersistencemutable

Kotlin - Persist MutableList on SharedPreferences


I've been playing around with Kotlin for Android. I have a mutable list which is a list of objects. Now I want to persist them, but I don't know what's the best way to do it. I think it can be done with SharedPreferences but I don't know how to parse the objects to a plain format or something. The objects are actually coming from a data class, maybe that can be useful.

Thanks


Solution

  • It is very easy to persist any data within SharedPreferences. All you need to do is get Gson implementation 'com.squareup.retrofit2:converter-gson:2.3.0' and then create class you would like to persist like this:

    class UserProfile {
    
        @SerializedName("name") var name: String = ""
        @SerializedName("email") var email: String = ""
        @SerializedName("age") var age: Int = 10
    
    }
    

    and finally in your SharedPreferences

    fun saveUserProfile(userProfile: UserProfile?) {
                val serializedUser = gson.toJson(userProfile)
                sharedPreferences.edit().putString(USER_PROFILE, serializedUser).apply()
            }
    
    
    fun readUserProfile(): UserProfile? {
                val serializedUser = sharedPreferences.getString(USER_PROFILE, null)
                return gson.fromJson(serializedUser, UserProfile::class.java)
            }