android-studio - SharedPreference 没有保存最后添加的 stringSet
问题描述
当我尝试将 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()
)
}
解决方案
我没有看到您在保存字符串后添加“.apply()”。
前任:
val orderPrefs = getSharedPreferences("order", Context.MODE_PRIVATE)
val editor = orderPrefs.edit()
editor.putStringSet("recentlyViewedRestaurant", test).apply()
推荐阅读
- c# - 如何让我的列表框包裹起来并显示为下拉列表
- ruby-on-rails - 如何在 QA 中预览 Rails 电子邮件?
- c# - 我可以减少 MDI 客户端窗口的可用区域吗?
- angular - 如何修复“未捕获(承诺):TypeError:this.upload.then 不是函数”Ionic Angular
- url - 您可以将变量存储在 URL 中吗?
- flutter - 如何在颤动中将键盘输入类型作为参数传递?
- javascript - 从样式组件宏重新导出样式不起作用
- javascript - 如何将值添加到减速器有效负载中的嵌套状态数组?
- java - 带有 Hibernate 的 JavaFX 桌面应用程序 - 无法识别 @Entity 和其他注释
- python - QListWidget 在文本附近显示项目编号