Multidimensional resource arrays in Android

Android allows you to define an XML resource called typed array which defines a list of other other resources (strings, drawables, etc.) whose items can be accessed using an integer index. Unfortunately these items cannot be typed arrays (as there is no method to access this type of item in the TypedArray class), so it is not possible to define multidimensional resource arrays that way.

As a two dimension resource array was exactly what I needed in one of my recent projects and I found a few hints but no good solution on the Internet I had to put something together myself. Here is what I came up with:

I put the array elements in several typed arrays with identifiers ending in ascending numbers:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <array name="myArray_0">
      <item>"string_0_0"</item>
      <item>"string_0_1"</item>
      <item>"string_0_2"</item>
      ...
   </array>
   <array name="myArray_1">
      <item>"string_1_0"</item>
      <item>"string_1_1"</item>
      <item>"string_1_2"</item>
      ... 
   </array>
   ...
</resources>

That means the array element myArray[x,y] contains the string “string_x_y” and is the y-th element of the typed array resource myArray_x.

For accessing the array elements I used reflection on Android’s R class as this blog post recommended it as the fastest method. Here is the code snippet:

import java.lang.reflect.Field;

Class<R.array> res;
Field field;

int x, y;
String myString;

x = ...
y = ...

try {
   res = R.array.class;
   field = res.getField("myArray_" + new Integer(x).toString());

   //set myString to the string resource myArray[x,y]
   myString = getResources().obtainTypedArray(field.getInt(null)).getString(y);

   ...

   catch (Exception e) {
      e.printStackTrace();
}

2 thoughts on “Multidimensional resource arrays in Android

  1. Pingback: Storing Multidimensional Resource Arrays in Android

Leave a Reply

Your email address will not be published. Required fields are marked *