1

As far as I can tell, values aren't stored in Android's SharedPreferences until they're explicitly accessed. That is, while they may have default values in XML, no value is placed in a SharedPreferences store until an accessor method is called, which is why all the accessors have "default" parameters included.

While this isn't a huge deal for simply pulling values out of the preference store, it prevents any attempt to get all the preference keys that are used in the application, even if they are stored in XML. The keys don't appear when SharedPreferences#getAll() is called unless the preference has already been explicitly accessed.

Is there any way to force all preferences defined in XML to be saved into a SharedPreferences store? The nearest solution I can find is to manually parse the Preference XML files, find all keys and defaults, and save the default value for each one. Is there a cleaner approach?

UPDATE

After looking at this in more depth, I've been getting a partial list of preferences for a different reason. When the defaults are set, only EditTextPreference and ListPreference values are saved. The other two, a custom preference and a CheckBoxPreference, are completely ignored. Here's an example of the CheckBoxPreference that's being ignored:

<CheckBoxPreference
    android:defaultValue="false"
    android:key="PREF_NAME"
    android:summary="Summary text"
    android:title="Title" />

Any idea why not all defaults are being set?

derekerdmann
  • 17,696
  • 11
  • 76
  • 110

2 Answers2

2

You can use PreferenceManager::setDefaultValues. For instance, at your Application::onCreate method.

PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

If the last argument is false, this will only set the default values if this method has never been called in the past.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Seems the problem's a bit more subtle, although that's certainly the right answer to the problem I thought I was having. – derekerdmann May 22 '12 at 20:01
  • I'm marking your answer as accepted since it answered the question I asked, and that's probably more likely to attract users than the real problem I encountered. – derekerdmann May 22 '12 at 20:29
0

The reason for the missing preferences in my case was actually an Android bug. The workaround was to manually set the missing preferences to their default values, as indicated in a duplicate question: Android CheckBoxPreference Default Value

Community
  • 1
  • 1
derekerdmann
  • 17,696
  • 11
  • 76
  • 110