【问题标题】:Kotlin :How to remove item stored in Array in shared preferenceKotlin:如何以共享首选项删除存储在数组中的项目
【发布时间】: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


【解决方案1】:

您的代码不起作用,因为ArrayListremove() 方法检查平等 以找到您要删除的对象。您应该在 ProductData 类中重写 equals() 方法,因为如果您不这样做,equals() 默认会检查 身份

class A(val id: Int)

val a1 = A(1)
val a2 = A(1)

a1 == a2 // false, they are different objects

更好的是,将ProductData 设为data class(生成正确的equals 和hashCode 方法)。

data class A(val id: Int)

val a1 = A(1)
val a2 = A(1)

a1 == a2 // true

我再给你一些建议:

  • 不要每次都实例化Gson:如果您一直使用默认配置,请重用该实例。您可以创建像defaultGson = Gson() 这样的顶级属性。这也适用于emptyList
  • 避免直接使用ArrayList,除非你有充分的理由:使用更通用的ListMutableList
  • 记得使用小写的参数名:DataArrayList 应该是dataArrayList
  • 如果你想监听 SharedPreference 的变化来更新你的 Activity,你可以使用sharedPreferences.registerOnSharedPreferenceChangeListener()。更好的方法是将 ViewModel 与 LiveData 一起使用,但我假设您仍在学习,所以我将把这个高级主题留到以后 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多