【问题标题】:SharedPreference is not saving the last added stringSet [duplicate]SharedPreference 没有保存最后添加的 stringSet [重复]
【发布时间】:2021-07-16 16:47:59
【问题描述】:

当我尝试将 stringSet 中的第一个字符串保存到它正常保存的 sharedPreferences 中时,但在尝试将另一个字符串保存在 stringSet 中之后,它显示为好像已保存但重新启动应用程序并检索数据时,它只显示保存的第一个字符串,当我再次尝试单击相同的功能按钮时,它不会保存到 sharedPreferecnes,但单击另一个具有相同功能的按钮将保存我觉得奇怪的前一个。这是我的代码

button.setOnClickListener {
    val orderPrefs = getSharedPreferences("order", Context.MODE_PRIVATE)
    val editor = orderPrefs.edit()
    var test = orderPrefs.getStringSet("recentlyViewedRestaurant", null)
    if (test == null) {
        test = HashSet<String>(0)
    }
    test.add(restaurantName)
    //Log.d("LastPicked", test.toString())
    editor.putStringSet("recentlyViewedRestaurant", test)
    editor.apply()
    val testing = getSharedPreferences("order", Context.MODE_PRIVATE)
    //it will retrieve and show the expected result but leaving the page
    //and retrieving from another activity won't show the last added string
    Log.d(
        "lastPicked",
        testing.getStringSet("recentlyViewedRestaurant", null).toString()
    )
}

【问题讨论】:

标签: android-studio kotlin sharedpreferences


【解决方案1】:

我没有看到你在保存字符串后添加“.apply()”。

例如:

val orderPrefs = getSharedPreferences("order", Context.MODE_PRIVATE)
val editor = orderPrefs.edit()

editor.putStringSet("recentlyViewedRestaurant", test).apply()

【讨论】:

  • OP 的代码中有commit()
  • 是的,我使用 commit() 作为标志
猜你喜欢
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 2016-11-06
  • 2019-05-24
  • 2017-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多