Search code examples
androidxmlarrayssettingsapplication-settings

Why do the entries on the list preference not show up in the app?


In the settings section, there is a list preference (as shown below in the code) for colours but I can't seem to find the reason why the values don't show up. I have checked the internet but I can't seem to understand the difference between android:entries and android:entryValues. Could this be a problem in my code? Any help is appreciated. Thanks in advance.

Array Below

<string-array name="preferencebackground">
<item name="Red"/>
<item name="Green"/>
<item name="Blue"/>
<item name="Orange"/>
</string-array>
<string name="preferencebackground">Background Colour Preferences</string>
 <string-array name="preferencebackgroundvalues">
<item name="Red"/>
<item name="Green"/>
<item name="Blue"/>
<item name="Orange"/>
</string-array>

Pref_general.xml

    <ListPreference
    android:defaultValue="-1"
    android:entries="@array/preferencebackground"
    android:entryValues="@array/preferencebackgroundvalues"
    android:key="example_list1"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/preferencebackground" />

Solution

  • The definitions of your arrays should look like:

    <string-array name="entries">
        <item>Red</item>
        <item>Blue</item>
        <item>Green</item>
        <item>Black</item>
    </string-array>
    
    <string-array name="values">
        <item>#FF0000</item>
        <item>#0000FF</item>
        <item>#00FF00</item>
        <item>#000000</item>
    </string-array>
    

    In addition, I'd remove these lines from the preferences ...

    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    

    ... and, more important: set a default value that is part of the list.

    <ListPreference
        android:defaultValue="Red"
        android:entries="@array/preferencebackground"
        android:entryValues="@array/preferencebackgroundvalues"
        android:key="example_list1"
        android:title="@string/preferencebackground" />
    

    Assuming you stored the arrays in a file called arrays.xml and the preferences file is well-formed as well, it should work without any issues.

    p.s. of course it's better to use a string reference instead of the hard-coded Red and color references instead of #FF0000 etc.