boolean SharedPreferences始终加载默认值

时间:2014-09-29 08:46:05

标签: android boolean sharedpreferences

我对 SharedPreferences 和布尔值有一个奇怪的问题。 我在xml中设置了这段代码:

xml:

 <CheckBoxPreference
             android:key="onlywifiupload"
             android:defaultValue="true"
             android:summary="@string/summary_onlywifiupload"
             android:title="@string/title_onlywifiupload" 
      />

从Java代码中我打电话:

 boolean onlywifiupload =  pref.getBoolean("onlywifiupload", true);

即使选中或取消选中复选框,只需在上传时,总是如此。 与设置相同:

 boolean onlywifiupload =  pref.getBoolean("onlywifiupload", false);

似乎始终加载默认值而不是检查值。

1 个答案:

答案 0 :(得分:1)

似乎让它运作的唯一方法是:

    mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    onlywifiupload = mPrefs.getBoolean("onlywifiupload", true);

我不知道为什么我需要从PrefenceManager对象调用getDefaultSharedPreferences

在此之前,我以这种方式调用首选项:

    pref = getSharedPreferences("AppPref", MODE_PRIVATE);