How to set the Default Value of a ListPreference

Solution 1:

You don't need to programmatically handle the default value of ListPreferences. You can do this in xml setting file. Below is an example

<string-array name="opts">
    <item>red</item>
    <item>green</item>
    <item>blue</item>
</string-array>

<string-array name="opts_values">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

...

<ListPreference
    android:title="Colour select"
    android:summary="Select your favourite"
    android:key="colour"
    android:entries="@array/opts"
    android:entryValues="@array/opts_values"
    android:defaultValue="2" />

here I selected 2 as a default value. Remember defaultvalue will be opts_values element.

Solution 2:

Have you tried:

setValueIndex(int index);

Solution 3:

Sorry my bad English.

  1. List item
  2. Retrieve the list Check if the value is null. If it is null set to the default value.

Code:

ListPreference dataPref = (ListPreference) findPreference("keyList");

if(dataPref.getValue() == null){
    dataPref.setValueIndex(0); //set to index of your deafult value
}

Solution 4:

You can set your default value by using the key like this

<string-array name="syncFrequency">
    <item name="1">Block All Calls</item>
    <item name="2">Block Black List</item>
    <item name="3">Block Unknown Calls</item>
    <item name="4">Allow White List</item>
    <item name="5">Receive All Calls</item>
</string-array>




<string-array name="syncFrequencyValues">
    <item name="1">Block_All_Calls</item>
    <item name="2">Block_Black_List</item>
    <item name="3">Block_Unknown_Calls</item>
    <item name="4">Allow_White_List</item>
    <item name="5">Receive_All_Calls</item>
</string-array>



     <ListPreference
        android:key="prefSyncFrequency"
        android:entries="@array/syncFrequency"
        android:summary="%s"
        android:defaultValue="Block_Black_List"
        android:entryValues="@array/syncFrequencyValues"
        android:title="@string/call_block_options" />