【问题标题】:SharedPreferences is not saving androidSharedPreferences 没有保存 android
【发布时间】: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 个默认值。在游戏活动中,如果这是应用程序第一次初始化,我应该获得默认值,否则它应该保留共享首选项中保存的值。

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    避免使用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();
    }
    

    【讨论】:

    • 感谢您的回复,但应用重启后这些值仍会恢复为原始值 :(
    【解决方案2】:

    这是有道理的,每次启动应用程序时都会运行启动屏幕活动代码。

    因此,您的SharedPreferences 总是会在启动画面中被覆盖。解决办法是将代码移到其他地方。

    【讨论】:

    • 如果我把这个添加到同一个计算量很大的活动中,它会和每次他们得到默认值一样吗?
    • 我需要进一步了解您的流程,因为启动是初始活动,您将哪个活动称为第一个和第二个活动,请更详细地编辑您的问题,以便我们对其进行整理
    【解决方案3】:

    我看到一个帖子检查共享首选项是否存在并且有效!!!

          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();
        }  
    

    【讨论】:

    • 不幸的是它再次崩溃:(
    【解决方案4】:

    编辑代码如下代码

    sharedPreferences = getSharedPreferences("App", context. MODE_PRIVATE);
        curlevel = sharedPreferences.getInt("LEVEL", "");
        goldcoins = sharedPreferences.getInt("COINS", "");
    

    【讨论】:

    • 它不允许我使用 getInt 与第二个参数“”?它建议我改用 getFloat?
    猜你喜欢
    • 2012-05-30
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2016-06-23
    • 2016-06-15
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多