How to retrieve 2D array from xml string resource for Android? How to retrieve 2D array from xml string resource for Android? xml xml

How to retrieve 2D array from xml string resource for Android?


The <string-array> element of a resources file can only be used for single dimension arrays. In other words, everything between <item> and </item> is considered to be a single string.

If you want to store data in the way you describe (effectively pseudo-XML), you'll need to get the items as a single String[] using getStringArray(...) and parse the <name> and <codes> elements yourself.

Personally I'd possibly go with a de-limited format such as...

<item>Bahrain,12345</item>

...then just use split(...).

Alternatively, define each <item> as a JSONObject such as...

<item>{"name":"Bahrain","code":"12345"}</item>


Instead of multi-valued entries, I wrote about another approach where you can store your complex objects as an array, then suffix the name with an incremental integer. Loop through them and create a list of strongly-typed objects from there if needed.

<resources>    <array name="categories_0">        <item>1</item>        <item>Food</item>    </array>    <array name="categories_1">        <item>2</item>        <item>Health</item>    </array>    <array name="categories_2">        <item>3</item>        <item>Garden</item>    </array><resources>

Then you can create a static method to retrieve them:

public class ResourceHelper {    public static List<TypedArray> getMultiTypedArray(Context context, String key) {        List<TypedArray> array = new ArrayList<>();        try {            Class<R.array> res = R.array.class;            Field field;            int counter = 0;            do {                field = res.getField(key + "_" + counter);                array.add(context.getResources().obtainTypedArray(field.getInt(null)));                counter++;            } while (field != null);        } catch (Exception e) {            e.printStackTrace();        } finally {            return array;        }    }}

It can be consumed like this now:

for (TypedArray item : ResourceHelper.getMultiTypedArray(this, "categories")) {    Category category = new Category();    category.ID = item.getInt(0, 0);    category.title = item.getString(1);    mCategories.add(category);}