Reputation: 1
We are trying to dynamically add an array in a java file to a xml file.
We have an ArrayList catList which is filled by reading a xml file from a website. The ArrayList is filled like this: [item1, item2, item3, item4, item5].
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<ListPreference
android:title="Ondernemer selecteren"
android:summary="Bij deze optie kunt U kiezen van welke ondernemer U de agenda wilt zien."
android:key="listPref"
android:defaultValue="Standaard"
android:entries="@array/ondernemerArray"
android:entryValues="@array/ondernemerValues"
/>
</PreferenceScreen>
arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="ondernemerArray">
<item></item>
</string-array>
<string-array name="ondernemerValues">
<item></item>
</string-array>
Does anyone know how we can put the catList array dynamically into the xml file, between the elements and dynamically increase the amount of elements?
Upvotes: 0
Views: 1070
Reputation: 2226
To fill a preference list with dynamic values you create the preference in settings.xml but do not specify its android:entries and android:entryValues properties.
<ListPreference
android:title="@string/pref_title"
android:summary="@string/pref_summary"
android:key="prefkey"
android:defaultValue="" />
Then you add some code in your preferences activity onCreate to fill the entries and entryValues from your xml data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
initializePreferenceList();
...
}
protected void initializePreferenceList(){
ListPreference lpPref = (ListPreference)findPreference("prefkey");
// Read your xml data somehow
...
// Write some methods to fill a String array from your xml data:
// something like toEntriesArray, toEntryValuesArray
String[] entries = toEntriesArray(xmlData);
String[] entryValues = toEntryValuesArray(xmlData);
lpPref.setEntries(entries);
lpPref.setEntryValues(entryValues);
}
You don't need to define any values in array.xml for this preference.
Upvotes: 1
Reputation: 44571
As stated in my comment, resources
can't be changed after they are compiled. So when you have things that need to be updated during runtime, such as an Array
here, you will need to use one of the several forms of persistent storage options available. Which one to use will depend on your data and your needs. If you don't need it to be persistent then you can use a static array
but it doesn't sound like that's what you need here.
The resources
mostly help keep from cluttering up your java code and aren't meant to be dynamic but more to make things easier for the developer as far as a place to store and reference things pre-compile. I know this isn't the answer you were looking for but hopefully that can help clear things up a bit about resources
.
If anyone has a better or more accurate description to add, feel free to edit
Upvotes: 0