skydoves / PreferenceRoom

:truck: Android processing library for managing SharedPreferences persistence efficiently and structurally.
Apache License 2.0
378 stars 26 forks source link

How to save List in using PreferenceRoom? #13

Closed steosoft closed 5 years ago

steosoft commented 5 years ago

I'm trying to save list of objects in preferences but I get compile error:

error: <identifier> expected
    MaterialTypeConverter converter = new MaterialTypeConverter(List<Material>.class);
                                                                               ^

Here's my PreferenceEntity:

@PreferenceEntity(name = "Prefs")
open class Prefs {
    @KeyName(name = "materials")
    @TypeConverter(converter = MaterialTypeConverter::class)
    @JvmField val materials: List<Material>? = null
}

and converter:

class MaterialTypeConverter(clazz: Class<List<Material>>): PreferenceTypeConverter<List<Material>>(clazz) {
    private val gson = Gson()

    override fun convertObject(obj: List<Material>): String = gson.toJson(obj)

    override fun convertType(string: String): List<Material> = Gson().fromJson(string, object : TypeToken<List<Material>>() {}.type)
}
skydoves commented 5 years ago

@steosoft It's fixed on new published version 1.1.5. Thank you for your issue!

ozanerturk commented 4 years ago

Could you please share some example code about using list with this library. I couldn't manage to work with lists. Beside It is not possible to give default value as an empty list instead of null.