我有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个默认值。在游戏活动中,我应该获得默认值,如果它是第一次初始化应用程序,它应该保留共享首选项中保存的值。
答案 0 :(得分:0)
避免使用clear()
方法:
public static void setPushEnabledFlag(Context context, String key ,int newValue) {
SharedPreferences prefs = context.getSharedPreferences("App", 0);
SharedPreferences.Editor prefsEditor = prefs.edit();
//prefsEditor.clear();
prefsEditor.putInt(key, newValue);
prefsEditor.commit();
}
答案 1 :(得分:0)
这是有道理的,每次启动应用程序时都会运行启动画面活动代码。
所以你的SharedPreferences
总是被覆盖。解决方案是将代码移动到不同的位置。
答案 2 :(得分:0)
按以下代码编辑代码
sharedPreferences = getSharedPreferences("App", context. MODE_PRIVATE);
curlevel = sharedPreferences.getInt("LEVEL", "");
goldcoins = sharedPreferences.getInt("COINS", "");
答案 3 :(得分:0)
我看到一个帖子检查是否存在共享偏好并且它可以正常工作!!!
SharedPreferences sharedPrefs = getSharedPreferences("App", 0);
SharedPreferences.Editor ed;
if(!sharedPrefs.contains("initialized")){
ed = sharedPrefs.edit();
//Indicate that the default shared prefs have been set
ed.putBoolean("initialized", true);
//Set some default shared pref
ed.putInt("LEVEL", 1);
ed.putInt("COINS", 100);
ed.commit();
}