Reputation: 861
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
Upvotes: 1
Views: 2688
Reputation: 444
Feel free to use this Kotlin extension functions to store and edit your list to SharedPreferences. I think they are realy useful.
inline fun <reified T> SharedPreferences.addItemToList(spListKey: String, item: T) {
val savedList = getList<T>(spListKey).toMutableList()
savedList.add(item)
val listJson = Gson().toJson(savedList)
edit { putString(spListKey, listJson) }
}
inline fun <reified T> SharedPreferences.removeItemFromList(spListKey: String, item: T) {
val savedList = getList<T>(spListKey).toMutableList()
savedList.remove(item)
val listJson = Gson().toJson(savedList)
edit {
putString(spListKey, listJson)
}
}
fun <T> SharedPreferences.putList(spListKey: String, list: List<T>) {
val listJson = Gson().toJson(list)
edit {
putString(spListKey, listJson)
}
}
inline fun <reified T> SharedPreferences.getList(spListKey: String): List<T> {
val listJson = getString(spListKey, "")
if (!listJson.isNullOrBlank()) {
val type = object : TypeToken<List<T>>() {}.type
return Gson().fromJson(listJson, type)
}
return listOf()
}
Upvotes: 0
Reputation: 126
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)
}
Upvotes: 3
Reputation: 357
For lists it think using sqlite will provide you with better control of your data. Check out anko's sqlite wiki for more info.
Upvotes: 1
Reputation: 407
Shared Preferences are mostly used in storing data like settings or configs, it's not meant for storing large data though it can do it as long as you implement Parcable
. If you think your data contained in your MutableList
is large, best way is to make a database.
Upvotes: 0