How-to init a ListPreference to one of its values
AndroidAndroid Problem Overview
I'm trying to set a defaultValue to a ListPreference item.
Here is an sample of my preference.xml file:
<ListPreference android:key="notification_delay"
android:title="@string/settings_push_delay"
android:entries="@array/settings_push_delay_human_value"
android:entryValues="@array/settings_push_delay_phone_value"
android:defaultValue="????">
</ListPreference>
The two arrays:
<string-array name="settings_push_delay_human_value">
<item>every 5 minutes</item>
<item>every 10 minutes</item>
<item>every 15 minutes</item>
</string-array>
<string-array
name="settings_push_delay_phone_value">
<item>300</item>
<item>600</item>
<item>900</item>
</string-array>
When i go into the preference activity, no item of the ListPreference is selected. I've tried to set an int value like 1 in the "android:defaultValue" fied to select "10 minutes" but it does not work.
<ListPreference android:key="notification_delay"
android:title="@string/settings_push_delay"
android:entries="@array/settings_push_delay_human_value"
android:entryValues="@array/settings_push_delay_phone_value"
android:defaultValue="1">
</ListPreference>
Any Idea?
Android Solutions
Solution 1 - Android
You need to specify the value. So to get the first entry selected by default specify defaultValue="300"
in your example.
Solution 2 - Android
Happened to be in same situation. Specifying a consistent default value. But graphically was not selected. I cleared the application data. And then it worked as expected. So a clear may be useful at dev time when adding new XxxPreference items.
Solution 3 - Android
In addition to Sven's answer, you have to call the setDefaultValues() method in the starting activity. This will set once all default values.
public class MainActivity extends Activity {
protected void onCreate(final Bundle savedInstanceState) {
// Set all default values once for this application
// This must be done in the 'Main' first activity
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
...
}
}
Solution 4 - Android
If it is a valid value from the list, then re-install the app. It will work.