Domanda

I'm trying to retrieve a default value:

Definition:

<integer name="keyOfDefaultValue">2</integer>

Referenced as:

android:defaultValue="@integer/keyOfDefaultValue"

Actual code:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int intVar = sharedPrefs.getInt(keyOfDefaultValue, fallbackIntValue);

I get ClassCastExceptions stating that I'm trying to cast String to an Integer. I've read the Android docs about default values:

http://developer.android.com/reference/android/preference/Preference.html#attr_android:defaultValue

so I expected to work with the correct type, but apparently I get a String.

Can someone confirm that default values defined in .xml are always to be retrieved as Strings? Or you could just point me to a page in the documentation where this is explained...

Thanks

È stato utile?

Soluzione

if you check the return value on AOSP code for different types of preference

EditTextPreference, ListPreference return String values

SwitchPreference,CheckBoxPreference returns boolean

MultiSelectListPreference returns a set of strings

If you want to change it, I guess you can always override onGetDefaultValue in your customPreference , if you have one

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top