Peterdk Peterdk - 5 months ago 38
Android Question

Android Preferences: How to load the default values when the user hasn't used the preferences-screen?

I am using a PreferenceActivity to let the user set some values.
I am feeding it the xml file with the defined preferences.

I have set all the

for them.

When I start my application, I need the preferences, or if they are not set yet manually, I want the default values:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean value = prefs.getBoolean("key"), false);

However, when
I still get
. So, it looks like the defaultValues set in the XML are not used anywhere but when initializing the preferences-screen.

I don't want to hardcode the default values in the
method. So, is there a way get the default-values with only defining these in 1 place?


this question is similar to mine:


Just use this code in onCreate method:

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

It will load your preferences from XML, and last parameter (readAgain) will guarantee that user preferences won't be overwritten.

Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.