11

How to Create Dynamic Array For ListPreference From Java Side.

I Don't use Below Xml .

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
 <item>Value 1</item>
 <item>Value 2</item>
<item>Value 3</item>
</string-array>

<string-array name="listValues">
 <item>1</item>
 <item>2</item>
 <item>3</item>
</string-array>
</resources>
david
  • 753
  • 4
  • 14
  • 26
  • Similar question: http://stackoverflow.com/questions/6474707/how-to-fill-listpreference-dynamically-when-onpreferenceclick-is-triggered – ccpizza Dec 11 '12 at 22:02

1 Answers1

23

Place preferences.xml in res/xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory android:title="Some title">     

        <ListPreference android:key="default_category"
            android:title="Dynamic categories" android:summary="Dynamic categories summary"
            android:defaultValue="0" />
    </PreferenceCategory>
</PreferenceScreen>

In your activity that extends PreferenceActivity you do something like this in onCreate().

ListPreference listPreferenceCategory = (ListPreference) findPreference("default_category");
if (listPreferenceCategory != null) {
    ArrayList<Category> categoryList = getCategories();
    CharSequence entries[] = new String[categoryList.size()];
    CharSequence entryValues[] = new String[categoryList.size()];
    int i = 0;
    for (Category category : categoryList) {
        entries[i] = category.getCategoryName();
        entryValues[i] = Integer.toString(i);
        i++;
    }
    listPreferenceCategory.setEntries(entries);
    listPreferenceCategory.setEntryValues(entryValues);
}
rochdev
  • 3,835
  • 2
  • 21
  • 18
  • code is work but clicked the listpreference then error exception? – david May 26 '11 at 10:45
  • your code is changed but clicked preference then raise error. – david May 26 '11 at 10:58
  • 05-26 14:01:55.925: ERROR/AndroidRuntime(4827): java.lang.NullPointerException – david May 26 '11 at 11:03
  • 05-26 14:01:55.925: ERROR/AndroidRuntime(4827): at android.preference.ListPreference.findIndexOfValue(ListPreference.java:169) – david May 26 '11 at 11:04
  • 05-26 14:01:55.925: ERROR/AndroidRuntime(4827): at android.preference.ListPreference.getValueIndex(ListPreference.java:178) – david May 26 '11 at 11:04
  • 1
    I happened to see you code before it was removed. int c = 0; for (int i=0; i<=ar.length-1; i++) { entries[c] = ar[c]; entryValues[c] = ar[c]; c++; } – rochdev May 26 '11 at 11:04