Kevin Vance - Storing Integers with Android ListPreference

Entries | Archive | Friends | Friends' Friends | User Info

11:23 pm

Storing Integers with Android ListPreference

Thursday, July 29th, 2010
Previous Entry Share Next Entry

Android has a nice built-in preferences framework, but it's a bit half-baked. A key ingredient of that framework is the ListPreference, a UI item that displays a list of options when clicked. The ListPreference is populated with an array of labels and a corresponding array of values, but the arrays are String-typed. Nectroid uses ListPreferences to select polling intervals and the IDs of database rows—integer types!

Here's a hackish solution that allows you to keep using ListPreference while having it store integers back to your app's preferences:

public class IntListPreference extends ListPreference
    public IntListPreference(Context context, AttributeSet attrs) {
        super(context, attrs);

    public IntListPreference(Context context) {

    protected boolean persistString(String value) {
        if(value == null) {
            return false;
        } else {
            return persistInt(Integer.valueOf(value));

    protected String getPersistedString(String defaultReturnValue) {
        if(getSharedPreferences().contains(getKey())) {
            int intValue = getPersistedInt(0);
            return String.valueOf(intValue);
        } else {
            return defaultReturnValue;

We override the persistString() and getPersistedString() methods to convert between string and integer, then call the corresponding persistInt() and getPersistedInt(). The backend stays String-based, with String values converted to ints right before they interact with the Preferences data store.

You can use the new IntListPreference widget in your preferences XML file by referring to its fully qualified name:

<com.kvance.example.IntListPreference android:title="@string/select_a_site"

Stupid, but not as stupid as copy-pasting the original and modifying it to use an int array!

Current Music Reyn Ouwehand - Asian Legends
Link )Reply )