views:

439

answers:

1

How do you get the default value of an Android preference defined in XML?

Context: I don't want to repeat the definition of the default value in both the code and the preferences XML.

+1  A: 

First you need to define default values in your preference XML file. Then you can populate preferences with default values in your main Activity by calling:

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

When you need to retrieve a some preference just call:

int value = prefs.getInt("key"), null);

Since your preferences are populated you won't get null value.

pixel
This still doesn't protect against the possible situation where someone down the line removes a preference from the XML and forgets to update the Java code requesting it. In that situation, the application will still compile, but you will end up with a NullPointerException.
mxrider
Yes, this is true, but then a Functional Test should be written to test if all needed preferences are retrieved from XML.
pixel