简体   繁体   中英

ListPreference throws 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/frequencies:

<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 are displayed correctly. However, if I try frequencyListPreference.setValueIndex(0); I get a NullPointerException. Even if I do nothing in my code, if I click on one of the elements of 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() is always null.

What am I doing wrong?

To my knowledge, Android will only accept String arrays instead of an 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 your code where you read from the Preference, use Integer.parseInt() to convert the value to a usable integer.

See the follow for more detail: ListPreference: use string-array as Entry and integer-array as Entry Values doesn't work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM