繁体   English   中英

sharedpreferences不会记住android中的值

[英]sharedpreferences wont remember values in android

这是我放置值的代码:

if(soundima == 1){
                        soundima=0;
                        editor.putInt("sOn", soundima);
                        editor.commit();
                    }
                    else if(soundima == 0){
                        soundima=1;
                        editor.putInt("sOn", soundima);
                        editor.commit();
                    }

然后,当我退出应用程序时,不会记住这些值。 我用这段代码得到了这些值:

editor = PreferenceManager.getDefaultSharedPreferences(this);
    soundima = editor.getInt("sOn", 0);

我不完全确定为什么这不起作用。 但是,以下代码应该可以解决问题。

//create a constant to use for the shared preferences
public static final String YOUR_CONSTANT = "Preferences";

然后,将值放在共享首选项中,使用以下代码:

if(soundima == 1){
    soundima = 0;
    SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
    SharedPreferences.Editor editor = sound.edit();
    editor.putInt("sOn", soundima);
    editor.commit();
}
else if(soundima == 0){
    soundima = 1;
    SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
    SharedPreferences.Editor editor = sound.edit();
    editor.putInt("sOn", soundima);
    editor.commit();
}

然后要检索值,请使用以下代码:

SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
soundima = sound.getInt("sOn", 0);

暂无
暂无

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

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