Search code examples
androidandroid-preferencespreferenceactivitypreferencelistpreference

Calling setDefaultValue() on a custom Preference class does not set the default value. Why?


I'm extending PreferenceActivity for my settings screen. In this preference activity i have a couple of preferences one of which is custom made. The problem is as follows:

in this custom preference (which extends from ListPreference) i want to be able to set the default value, so i override the setDefaultValue() method. In this method i do some parsing so it'll take the correct value. When i'm trying to read this value with the getValue() function it just returns null.

So i figured, what happens when i just put some hardcoded value in there (you know, maybe i did something wrong, wouldn't be the first time). Well, i still get null back.

Any ideas what i'm doing wrong?

Edit:
Setting the defaultValue in the xml file isn't really an option because the values aren't known until i retrieve them.

I made a workaround:

  • When app is started for the first time: get data
  • Set the values in the preference.

This way i set the default preference when i'm collection the data


Solution

  • setDefaultValue doesn't work the way you think it does. Look at the source of Preference.java and you'll the logic behind it all.

    The preferred way to set a default is to specify the android:defaultValue attribute in the preferences.xml file of your app.