【发布时间】:2015-03-25 00:01:15
【问题描述】:
我有 2 个共享首选项,在应用重新启动后似乎没有保存。下面是我的代码。
这是我创建共享首选项的初始屏幕:
SharedPreferences settings = getSharedPreferences("App", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("LEVEL", 1);
editor.putInt("COINS", 100);
editor.commit();
当应用程序进入下一个活动时,我对存储的值进行了一些操作,并且所有内容似乎都在这个活动中工作。我把它放在活动创建上
sharedPreferences = getApplicationContext().getSharedPreferences("App", 0);
curlevel = sharedPreferences.getInt("LEVEL", 0);
goldcoins = sharedPreferences.getInt("COINS", 0);
然后我根据以下函数更新值:
public static void setPushEnabledFlag(Context context, String key ,int newValue) {
SharedPreferences prefs = context.getSharedPreferences("App", 0);
Editor prefsEditor = prefs.edit();
prefsEditor.clear();
prefsEditor.putInt(key, newValue);
prefsEditor.commit();
}
每次我重新启动应用程序时,这些值都会恢复为第一个活动的原始值。
有什么帮助吗?
编辑 1:
我只有 2 个活动,Splash 和游戏,在第一个活动中,我必须创建共享首选项并为 COINS 和 LEVEL 分配 2 个默认值。在游戏活动中,如果这是应用程序第一次初始化,我应该获得默认值,否则它应该保留共享首选项中保存的值。
【问题讨论】: