ListPreference: use string-array as Entry and integer-array as Entry Values doesn't work ListPreference: use string-array as Entry and integer-array as Entry Values doesn't work android android

ListPreference: use string-array as Entry and integer-array as Entry Values doesn't work


The answer is simple: because the Android is designed this way. It just uses String arrays for both entries and entry values and that's all. And I can't see any problem in this fact, since you can easily convert a String to an int using the Integer.parseInt() method. Hope this helps.


You can convert your entry values to strings to keep ListPreference happy and then convert them to ints when talking to the persistent data store.

  1. When setting the entry values, use strings instead of ints: "1", "2", "3" etc
  2. Make a custom IntListPreference that persists the values as ints
  3. In your preferences.xml file, change the <ListPreference> into a <your.app.package.IntListPreference>

IntListPreference.java

Here's a sample implementation. Tested and working on AndroidX Preference 1.0.0.

public class IntListPreference extends ListPreference {    public IntListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {        super(context, attrs, defStyleAttr, defStyleRes);    }    public IntListPreference(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public IntListPreference(Context context, AttributeSet attrs) {        super(context, attrs);    }    public IntListPreference(Context context) {        super(context);    }    @Override    protected boolean persistString(String value) {        int intValue = Integer.parseInt(value);        return persistInt(intValue);    }    @Override    protected String getPersistedString(String defaultReturnValue) {        int intValue;        if (defaultReturnValue != null) {            int intDefaultReturnValue = Integer.parseInt(defaultReturnValue);            intValue = getPersistedInt(intDefaultReturnValue);        } else {            // We haven't been given a default return value, but we need to specify one when retrieving the value            if (getPersistedInt(0) == getPersistedInt(1)) {                // The default value is being ignored, so we're good to go                intValue = getPersistedInt(0);            } else {                throw new IllegalArgumentException("Cannot get an int without a default return value");            }        }        return Integer.toString(intValue);    }}


The answer is listed in List Preference Documentation.

int findIndexOfValue (String value)

will return the index for given value and the argument is taken as a String, so the entryValues array should be a string array to get this work.