Kotlin - 在 SharedPreferences 上保留 MutableList

Kotlin - Persist MutableList on SharedPreferences

我一直在研究 Kotlin Android。我有一个可变列表,它是一个对象列表。现在我想坚持他们,但我不知道最好的方法是什么。我认为这可以通过 SharedPreferences 来完成,但我不知道如何将对象解析为纯格式或其他格式。这些对象实际上来自数据 class,也许这很有用。

谢谢

您也可以使用 Firebase 来实现数据持久化,您可以使用 SharedPreferences,但我个人觉得使用 Firebase 更容易和舒适。 我将在此处留下 link,以便您可以查看 Firebase 的磁盘持久性行为。
希望对您有所帮助!

共享首选项主要用于存储设置或配置等数据,它并不意味着存储大数据,但只要您实现 Parcable 就可以。如果您认为 MutableList 中包含的数据很大,最好的方法是建立一个数据库。

对于它认为使用 sqlite 的列表,您可以更好地控制数据。 查看 anko's sqlite wiki 了解更多信息。

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

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

随意使用此 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()
}