【问题标题】:How to add item to list stored in sharedPreferences?如何将项目添加到存储在 sharedPreferences 中的列表中?
【发布时间】:2022-01-11 16:40:16
【问题描述】:

我正在尝试使用 sharedPreferences 在本地存储中存储字符串列表 当我第一次为我的应用程序提供午餐时,存储库应返回null。 当我尝试将任何新项目写入我的存储然后读取它时,功能

getSearchHistoryItems()

不返回任何数据。我写的函数有问题吗 新项目?

interface LocalPreferencesRepository {
    fun getSearchHistoryItems(): List<String>?
    fun addSearchHistoryItem(item: String)
}

class LocalPreferencesRepositoryImpl(
    private val sharedPreferences: SharedPreferences
) : LocalPreferencesRepository {

    override fun getSearchHistoryItems(): List<String>? {
        return Gson().fromJson(
            sharedPreferences.getString(PREF_SEARCH_HISTORY, null),
            object : TypeToken<ArrayList<String>>() {}.type
        )
    }

    override fun addSearchHistoryItem(item: String) {
        val listToSave = listOf(item).plus(getSearchHistoryItems())
        val json = Gson().toJson(listToSave)
        with(sharedPreferences.edit()) { putString(PREF_SEARCH_HISTORY, json); commit() }
    }

    companion object {
        private const val PREF_SEARCH_HISTORY = "PREF_SEARCH_HISTORY"
    }
}

编辑:

override fun getSearchHistoryItems(): List<String>? =
        try {
            Gson().fromJson(
                sharedPreferences.getString(PREF_SEARCH_HISTORY, "").orEmpty(),
                object : TypeToken<ArrayList<String>>() {}.type
            )
        } catch (e: Exception) {
            null
        }

【问题讨论】:

    标签: android kotlin arraylist sharedpreferences


    【解决方案1】:

    listToSave 是一个List&lt;Any&gt;,因为List&lt;String&gt; + List&lt;String&gt;? 将使用plus 的重载,它将第二个参数添加为单个元素,而不是迭代它并添加其所有项目。为什么不让getSearchHistoryItems() 返回一个不可为空的列表(返回.orEmpty())?

    另外,我认为当 SharedPreference 中当前没有存储任何内容时,您将面临崩溃的危险。我用的Gson不多,但是如果你传一个无效的Json String或者null,它不会抛出异常吗?

    另外,一个小费。有一个 KTX 扩展函数 SharedPreferences.edit 函数可以让您传递一个 lambda,您可以在其中进行编辑,而不必手动提交。使用起来稍微干净一点。默认情况下,它在内部使用apply() 而不是commit(),这是您通常应该做的事情。如果您确实需要保证在返回之前有写入,则应该使用协程或使用 Jetpack Datastore 而不是 SharedPreferences。

    interface LocalPreferencesRepository {
        fun getSearchHistoryItems(): List<String>
        fun addSearchHistoryItem(item: String)
    }
    
    class LocalPreferencesRepositoryImpl(
        private val sharedPreferences: SharedPreferences
    ) : LocalPreferencesRepository {
    
        override fun getSearchHistoryItems(): List<String> {
            return Gson().fromJson(
                sharedPreferences.getString(PREF_SEARCH_HISTORY, ""),
                object : TypeToken<ArrayList<String>>() {}.type
            ).orEmpty()
        }
    
        override fun addSearchHistoryItem(item: String) {
            val listToSave = listOf(item).plus(getSearchHistoryItems())
            val json = Gson().toJson(listToSave)
            sharedPreferences.edit { putString(PREF_SEARCH_HISTORY, json) }
        }
    
        companion object {
            private const val PREF_SEARCH_HISTORY = "PREF_SEARCH_HISTORY"
        }
    }
    

    【讨论】:

    • 感谢您的建议
    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2016-07-18
    • 2022-09-30
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多