【发布时间】:2019-09-10 12:20:31
【问题描述】:
我想从存储在 sharedPreferences 中的数组(键)中删除一个项目(id = "productId")。 我编写了一个实用程序类,其中包含以下所有这些函数,但该项目仍然存在于存储的数组中,我该如何更改我的代码以达到我的目标。
fun removeArrayDataByKeyValue(key: String, productId: String) {
val prod = getDataInArrayList(key)
val removeProduct = ProductData(
id = productId)
prod.remove(removeProduct)
if (prod != null) {
setDataInArrayList(prod, key)
}
}
fun setDataInArrayList(DataArrayList: ArrayList<ProductData>, key: String) {
val jsonString = Gson().toJson(DataArrayList)
sharedPreferences.edit().putString(key, jsonString).apply()
}
fun getDataInArrayList(key: String): ArrayList<ProductData> {
val emptyList = Gson().toJson(ArrayList<ProductData>())
return Gson().fromJson(
sharedPreferences.getString(key, emptyList),
object : TypeToken<ArrayList<ProductData>>() {
}.type
)
}
我的活动中的以下代码:
Utility(this).removeArrayDataByKeyValue("FavoritesProducts", productFavoris.id.toString())
Toast.makeText(this, "Removed from favorites", Toast.LENGTH_LONG).show()
buttonAddToFavorite.setColorFilter(Color.parseColor("#FF000000"))
finish()
startActivity(intent)
【问题讨论】:
-
您的项目不在您的
SharedPreferences中。它在您的SharedPreferences中的某个 JSON 字符串中。您需要getDataInArrayList(key),从返回的ArrayList中删除具有匹配productId的项目,然后将setDataInArrayList(newList, key)重新放入SharedPreferences。 -
我认为我所做的不是?
-
不,你的中间步骤是错误的——
sharedPreferences.edit().remove(productId).apply()。这是试图从SharedPreferences中删除一个键/值。您需要从prod列表中删除与productId匹配的项目。 -
我在上面的代码中改变了乐趣,你能告诉我我应该怎么做
-
是的,这很可能行不通。我自己对 Kotlin 还是很陌生,但我认为你可以做一些类似
prod.removeAll { it.id == productId }的事情。
标签: android kotlin sharedpreferences