views:

1352

answers:

2

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 android:defaultValue="" 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 android:defaultValue="true" I still get false. 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 getBoolean() method. So, is there a way get the default-values with only defining these in 1 place?

A: 

For example extending DialogPreference I do this:

@Override
protected void onSetInitialValue(boolean restore, Object defaultValue) {
    super.onSetInitialValue(restore, defaultValue);

    if (restore) {
        mValue = shouldPersist() ? getPersistedString(mDefault) : mDefault;
    } else {
        mValue = mDefault;
    }
}

mDefault can be:

  • mContext.getResources().getString(attrs.getAttributeResourceValue(androidns,"defaultValue", 100));
  • something you have indexed in R.
Macarse
Ok, I am a bit lost here about what you are trying to achieve. I don't want to call DialogPreference, I need the default value when the user doesn't user the Preferences.
Peterdk
Instead of using default Preferences in your prefs.xml you can create your own classes. For example you can create a new DialogPreference extending from DialogPreference and override the onSetInitialValue.
Macarse
+3  A: 

Hi, this question is similar to mine:

initialize-preferences-from-xml-in-main-activity

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.

pixel
Hmm, sounds very promising! Will look into it later.
Peterdk