I have set up a PreferenceFragment
with two boolean preferences. The Fragment
works fine and the settings are stored when the app is closed and reopened. I am, however, having issues while trying to read these values; only the default value is returned. If I debug into the getBoolean
method of SharedPreferences
I see that the local HashMap
is of size 0, hence the default value is returned, like this:
public boolean getBoolean(String key, boolean defValue) {
synchronized (this) {
awaitLoadedLocked();
Boolean v = (Boolean)mMap.get(key); // <-- mMap is of size 0: return defValue
return v != null ? v : defValue;
}
}
I find this strange since the preference values are obviously stored and loaded properly into the PreferenceFragment
. What am I missing?
In Activity.onCreate()
:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
res/xml/preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="mm_preferences_category_recipe_preferences"
android:title="@string/mm_preferences_category_recipe_preferences_title" >
<CheckBoxPreference
android:key="@string/mm_preferences_numbers_as_fractions_key"
android:title="@string/mm_preferences_numbers_as_fractions_title"
android:summary="@string/mm_preferences_numbers_as_fractions_summary"
android:defaultValue="true" />
<CheckBoxPreference
android:key="@string/mm_preferences_comma_as_decimal_separator_key"
android:title="@string/mm_preferences_comma_as_decimal_separator_title"
android:summary="@string/mm_preferences_comma_as_decimal_separator_summary"
android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>
My PreferenceFragment
class:
public class MiasMatPreferencesFragment extends PreferenceFragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Now, doing this anywhere in the app, returns only the default values (true in both cases), even though the PreferenceFragment
shows that the values are set to false (if so):
boolean foo = getPreferences(Context.MODE_PRIVATE).getBoolean(getString(R.string.mm_preferences_numbers_as_fractions_key), true);
boolean bar = getPreferences(Context.MODE_PRIVATE).getBoolean(getString(R.string.mm_preferences_comma_as_decimal_separator_key), true);