Kotlin - 在SharedPreferences上持久化MutableList

时间:2017-08-28 20:38:51

标签: android sharedpreferences kotlin persistence mutable

我一直在玩Kotlin for Android。我有一个可变列表,它是一个对象列表。现在我想坚持下去,但我不知道最好的方法是什么。我认为可以使用SharedPreferences完成,但我不知道如何将对象解析为普通格式或其他东西。对象实际上来自数据类,也许这可能很有用。

由于

5 个答案:

答案 0 :(得分:1)

您也可以使用Firebase进行数据持久化,您可以使用SharedPreferences,但我个人觉得使用Firebase更加轻松和舒适。 我将在此处留下链接,以便您查看Firebase的磁盘持久性行为。
希望这能帮到你!

答案 1 :(得分:1)

对于列表,它认为使用sqlite将为您提供更好的数据控制。 查看anko's sqlite wiki了解详情。

答案 2 :(得分:1)

在SharedPreferences中保存任何数据非常容易。您需要做的就是获取 Gson implementation 'com.squareup.retrofit2:converter-gson:2.3.0',然后创建您想要坚持的课程:

class UserProfile {

    @SerializedName("name") var name: String = ""
    @SerializedName("email") var email: String = ""
    @SerializedName("age") var age: Int = 10

}

最后在您的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)
        }

答案 3 :(得分:0)

共享首选项主要用于存储设置或配置等数据,虽然只要您实现Parcable,但它不能用于存储大数据。如果您认为MutableList中包含的数据很大,最好的方法是建立数据库。

答案 4 :(得分:0)

可以随时使用此 Kotlin 扩展功能来存储列表并将其编辑为SharedPreferences。我认为它们真的很有用。

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()
}