简体   繁体   English

在 Android 中保存和检索数据

[英]Saving and retrieving data in 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"
}

I've made a simple game and I need to store the the highscore value and retrieve the value when the app is relaunched.我制作了一个简单的游戏,我需要存储高分值并在重新启动应用程序时检索该值。 I've tried to use sharedPreferences in the given code.我尝试在给定的代码中使用 sharedPreferences 。 But the highscore data is lost when I close the app and relaunch it.但是当我关闭应用程序并重新启动它时,高分数据会丢失。 How can I save and retrieve the value?如何保存和检索值? PS: The highscore value is saved/retrieved properly when running the app in Android Studio's emulator. PS:在 Android Studio 的模拟器中运行应用程序时,可以正确保存/检索高分值。 But it doesn't work when I run the app on my phone.但是当我在手机上运行该应用程序时它不起作用。 It resets to 0 every time I relaunch it.每次我重新启动它时它都会重置为0。

you are trying to save, when the app is destroyed.当应用程序被破坏时,您正在尝试保存。 This might work sometimes, when onDestroy is actually called, but that does not happen for sure.有时,当实际调用 onDestroy 时,这可能会起作用,但这肯定不会发生。

Apply is saving the data asynchronous to the disk, which won't happen as you are trying to do it when the app is destroyed. Apply 将数据异步保存到磁盘,当应用程序被销毁时,这不会发生,因为您尝试这样做。 You have to use commit instead of apply to save the data synchronous.您必须使用 commit 而不是 apply 来同步保存数据。

I would recommend to save the data at another point of your app instead of in onDestroy, as this won't be called every time the app is closed/killed.我建议将数据保存在应用程序的另一个点而不是 onDestroy 中,因为每次应用程序关闭/终止时都不会调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM