【发布时间】: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