首页 > 解决方案 > 在 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。

标签: androidandroid-studiokotlinsharedpreferences

解决方案


当应用程序被破坏时,您正在尝试保存。有时,当实际调用 onDestroy 时,这可能会起作用,但这肯定不会发生。

Apply 将数据异步保存到磁盘,当应用程序被销毁时,这不会发生,因为您尝试这样做。您必须使用 commit 而不是 apply 来同步保存数据。

我建议将数据保存在应用程序的另一个点而不是 onDestroy 中,因为每次应用程序关闭/终止时都不会调用它。


推荐阅读