gpt4 book ai didi

java - Android:SharedPreferences 在关闭应用程序后丢失 2 个变量

转载 作者:行者123 更新时间:2023-12-02 02:39:18 25 4
gpt4 key购买 nike

我通过 SharedPreferences 保存了几个变量,没有出现任何问题。但是,在我重新启动应用程序后,其中 2 个变量会被重置。我认为问题发生在保存时,而不是加载时,因为如果我更改加载的默认值,它甚至不使用该值,它只是变为 0。

我在onPause中调用这个方法:

public void saveStats() {
SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCES, this.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();

editor.putLong(SECONDS_PLAYED_TOTAL_FILE, secondsPlayedTotal);
editor.putFloat(CURRENCY_GAINED_TOTAL_FILE, currencyGainedTotal);
editor.apply();
}

并加载 onResum:

SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCES, this.MODE_PRIVATE);
SECONDS_PLAYED_TOTAL = pref.getLong(SECONDS_PLAYED_TOTAL_FILE, 0);
CURRENCY_GAINED_TOTAL = pref.getFloat(CURRENCY_GAINED_TOTAL_FILE, 0);

变量是公共(public)的和静态的。我保存和加载类似的公共(public)静态变量没有任何问题,但这两个是我在 onPause() 中保存的唯一变量。

有什么想法吗?

最佳答案

您可以尝试将 editor.apply(); 替换为 editor.commit()

来自 Android 文档:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.

链接: https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

关于java - Android:SharedPreferences 在关闭应用程序后丢失 2 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45746743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com