Java – ListPreference throws a NullPointerException

ListPreference throws a NullPointerException… here is a solution to the problem.

ListPreference throws a NullPointerException

I have a ListPreference:

    <ListPreference
        android:entries="@array/frequencies"
        android:entryValues="@array/frequencies_values"
        android:key="pref_key_frequencies"
        android:summary="@string/frequency_pref_summary"
        android:title="@string/frequency_pref_title" />

@array/frequency:

<string-array name="frequencies">
    <item>5 minutes</item>
    <item>10 minutes</item>
    <item>15 minutes</item>
    <item>20 minutes</item>
    <item>30 minutes</item>
    <item>60 minutes</item>
</string-array>

@array/frequencies_values

<integer-array name="frequencies_values">
    <item>300</item>
    <item>600</item>
    <item>900</item>
    <item>1200</item>
    <item>1800</item>
    <item>3600</item>
</integer-array>

The elements in the dialog box are displayed correctly. However, if I try frequencyListPreference.setValueIndex(0); , I get NullPointerException.
Even if I do nothing in my code, if I click on an element in the list, I get:

    java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference

If I check the value of one of the elements of the array frequencyListPreference.getEntryValues(), the value is always null.

What am I doing wrong?

Solution

As far as I know, Android only accepts arrays of strings and not integers.

Change

<integer-array name="frequencies_values">
    <item>300</item>
    <item>600</item>
    <item>900</item>
    <item>1200</item>
    <item>1800</item>
    <item>3600</item>
</integer-array>

to

<string-array name="frequencies_values">
    <item>300</item>
    <item>600</item>
    <item>900</item>
    <item>1200</item>
    <item>1800</item>
    <item>3600</item>
</string-array>

In the code that you read from the preferences, use Integer.parseInt() to convert the value to a usable integer.

For more information, see the following: ListPreference: use string-array as Entry and integer-array as Entry Values doesn’t work

Related Problems and Solutions