Java – How do I get values from typed array resources by name in Android?

How do I get values from typed array resources by name in Android?… here is a solution to the problem.

How do I get values from typed array resources by name in Android?

Let’s say I have a resource xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <array name="difficulties">
        <item>
            <integer name="level">1</integer>
            <integer name="fixed_blocks">2</integer>
            <integer name="color_count">2</integer>
        </item>
        <item>
            <integer name="level">2</integer>
            <integer name="fixed_blocks">4</integer>
            <integer name="color_count">3</integer>
        </item>
        <item>
            <integer name="level">3</integer>
            <integer name="fixed_blocks">6</integer>
            <integer name="color_count">3</integer>
        </item>
    </array>    
</resources>

How to get integer value from item by name? TypedValue's API doesn’t seem to contain any methods. What if this is not possible with TypedArray?

If I can get the value from the project by ordinal, that’s okay too.

Solution

I

don’t remember it was possible (but I could be wrong). Depending on the structure of the project (in the difficulties array), you can do other things, you can use an array of integer arrays. Knowing that the item array has level in the first position, fixed_blocks in the second position, etc., you can easily get the value. You can find examples of this hereAndroid Resource – Array of Arrays

Edit:
Is this the method you are looking for?

private int[] getLevelConstants(int level) {
    int[] result = null;
    TypedArray ta = getResources().obtainTypedArray(R.array.difficulties);
     keep in mind the differences between the level(starts at 1) and the index of the difficulties array which starts at 0
    int id = ta.getResourceId(level, 0); 
    if (id > 0) {
        result = getResources().getIntArray(id);
    } else {
         something bad
    }
    return result;
}

The array will be:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<integer-array name="difficulties">
        <item>@array/level1</item>
        <item>@array/level2</item>
    </integer-array>

<integer-array name="level1" >
        <item>1</item>
        <item>2</item>
        <item>2</item>
    </integer-array>

<integer-array name="level2" >
        <item>2</item>
        <item>4</item>
        <item>3</item>
    </integer-array>

</resources>

Related Problems and Solutions