Java – How do I get the default value for a ListPreference defined in XML?

How do I get the default value for a ListPreference defined in XML?… here is a solution to the problem.

How do I get the default value for a ListPreference defined in XML?

How do I programmatically get the default value for a ListPreference defined in XML?

This is the fragment of my ListPreference :

    <ListPreference
        android:defaultValue="60"
        android:entries="@array/interval_entries"
        android:entryValues="@array/interval_values"
        android:key="interval"
        android:summary="@string/interval_summary"
        android:title="@string/interval_title" />

I’ve read the docs, but I haven’t found a way to get it yet. Maybe I overlooked it.

Solution

For PreferenceActivity (deprecated Fragment), try:

ListPreference lp = (ListPreference) this.findPreference(this.getString(R.string.my_key));
lp.getValue();

where my_key is the key value assigned to this ListPreference Note: This value is defined in strings.xml. If you have hardcoded the key with a literal string, replace my_key with any strings you provided for the android:key tag. So, in your case, the code will be:

ListPreference lp = (ListPreference) this.findPreference("interval");
lp.getValue();

Related Problems and Solutions