android - 在 Android 中保存和检索数据
问题描述
private var highScore: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_game)
loadData()
playGame()
}
override fun onDestroy() {
super.onDestroy()
saveData()
}
private fun saveData(){
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.apply{
putInt("INTEGER_KEY", highScore)
}.apply()
}
private fun loadData(){
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val savedInt = sharedPreferences.getInt("INTEGER_KEY", 0)
highScore = savedInt
binding.highScore.text = "Highscore: $savedInt"
}
我制作了一个简单的游戏,我需要存储高分值并在重新启动应用程序时检索该值。我尝试在给定的代码中使用 sharedPreferences 。但是当我关闭应用程序并重新启动它时,高分数据会丢失。如何保存和检索值?PS:在 Android Studio 的模拟器中运行应用程序时,会正确保存/检索高分值。但是当我在手机上运行该应用程序时它不起作用。每次我重新启动它时它都会重置为0。
解决方案
当应用程序被破坏时,您正在尝试保存。有时,当实际调用 onDestroy 时,这可能会起作用,但这肯定不会发生。
Apply 将数据异步保存到磁盘,当应用程序被销毁时,这不会发生,因为您尝试这样做。您必须使用 commit 而不是 apply 来同步保存数据。
我建议将数据保存在应用程序的另一个点而不是 onDestroy 中,因为每次应用程序关闭/终止时都不会调用它。
推荐阅读
- sql-server - SQL Server 查询运行 - 但未返回任何数据
- android - 点击后退按钮后存储变量
- vim - 在 Vim 上设置颜色主题
- python - 取一个列表,根据连续的重复值返回一个 True/False 列表
- android - 返回总和和平均使用房间
- asp.net-core - ASP.Net Core - 使用 WebAPI 和 MVC 前端的 JWT 身份验证不起作用
- sparql - 当您有多字和缩略字符时,在 sparql 中进行自由文本搜索
- database - Aerospike ACID - 如何知道超时事务的最终结果?
- c# - 如何在 HDF5 C# 上创建复合数据集
- android - ViewPager 中包含的 Fragment 内的 RecyclerView 为空