我正在嘗試將字串串列存盤在本地存盤中,使用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
}
uj5u.com熱心網友回復:
listToSave是List<Any>因為List<String> List<String>?將使用的多載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"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/409911.html
標籤:
