提交后,Android SharedPreferences为空

时间:2016-11-17 10:50:16

标签: android sharedpreferences

为什么在以下示例中foo为false?

mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs.edit().putBoolean("myValue",true);
mPrefs.edit().commit();

boolean foo = mPrefs.getBoolean("myValue",false);

5 个答案:

答案 0 :(得分:3)

我认为你必须以这种方式写作

mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs.edit().putBoolean("myValue",true).commit();

boolean foo = mPrefs.getBoolean("myValue",false);

答案 1 :(得分:1)

第一次拨打edit()时,您没有保存boolean,因此在检索时它不存在。

mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs.edit().putBoolean("myValue",true).commit();
boolean foo = mPrefs.getBoolean("myValue",false);

答案 2 :(得分:0)

按--->存储您的值

SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("myValue",true);
editor.apply();

获得结果--->

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean b = sharedPreferences.getboolean("myValue","");

答案 3 :(得分:-1)

您应Edit通过SharedPreference

Editor对象SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("Key", value); editor.commit();
group by

答案 4 :(得分:-1)

在共享偏好设置中保存价值:

SharedPreferences settings =getSharedPreferences("AppName", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(key, value);
    editor. putBoolean(key, value);
            editor.commit();

从共享偏好中获取价值:

  SharedPreferences settings = getSharedPreferences("AppName", 0);
            String value=settings.getString(key, ""); 
    boolean value=settings.getBoolean(key,false);