Skip to content Skip to sidebar Skip to footer

How To Retrieve 2d Array From Xml String Resource For Android?

Suppose I have stored a 2 dimensional array in android resource as shown below. How can I get them in a java collection like Arraylist? 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>

Solution 2:

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><arrayname="categories_0"><item>1</item><item>Food</item></array><arrayname="categories_1"><item>2</item><item>Health</item></array><arrayname="categories_2"><item>3</item><item>Garden</item></array><resources>

Then you can create a static method to retrieve them:

publicclassResourceHelper{

    publicstaticList<TypedArray> getMultiTypedArray(Context context, String key) {
        List<TypedArray> array = new ArrayList<>();

        try {
            Class<R.array> res = R.array.class;
            Fieldfield;
            intcounter = 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 {
            returnarray;
        }
    }
}

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);
}

Post a Comment for "How To Retrieve 2d Array From Xml String Resource For Android?"