Android f11labz

Creating a double dimensional array from resources in Android

Android has a very nice mechanisim to switch the strings according to the locale.
All the developer has to do is keep translated version of strings.xml in different folders as per the locale guidelines and the android firmware will take care of the same.
Storing the values of a single dimension array is very straight forward , however it is slightly tricky when it comes to double dimension array.

Create a resource file in res/values folder called arrays.xml.

Inside it create a couple of arrays like so

<string-array name="friday">

<string-array name="monday">

In the above the items are present in the string.xml file.
Now create an array of arrays in the same file like so

<array name="words">

Each item above refers to an array , while those arrays in turn refers to items from the string.xml
Now lets have a look at the strings.xml file.

<string name="friday_one">Friday Night fever</string>
<string name="friday_two">TGIF</string>
<string name="friday_three">I am dog tired</string>
<string name="mon_one">I hate monday</string>
<string name="mon_two">Hell starts</string>
<string name="mon_three">Quit Monday</string>

Well as expected the values of the items referred to by the array.

Now lets have a look at the the code to access the same from the code .

Resources res = getResources();
TypedArray ta = res.obtainTypedArray(R.array.words);
Map<String, List<String>> wordMap = new HashMap<String, List<String>>();

int n = ta.length();
for (int i = 0; i < n; ++i)
//String key = ta.get;
int resId = ta.getResourceId(i, 0);
String key = res.getResourceEntryName(resId);
List<String> values = Arrays.asList(res.getStringArray(resId));
wordMap.put(key, values);


for (String key : wordMap.keySet())

Log.e(" Test ","Key is "+key);
for ( String value : wordMap.get(key))
Log.e(" Test ","Vlaue is "+value);

The code is simple really , first reading the typed array words from the resources arrays.xml
This contains the two arrays “friday” and “monday”.
Now the trick is to get the resource ids for those arrays and then return them as one dimensional array , I am then storing them as a map with the key as the array name.

It is important to do ta.recycle() to release the reosurces .

Printing the values will give the output

Test ( 339): Key is friday
E/ Test ( 339): Vlaue is Friday Night fever
E/ Test ( 339): Vlaue is TGIF
E/ Test ( 339): Vlaue is I am dog tired
E/ Test ( 339): Key is monday
E/ Test ( 339): Vlaue is I hate monday
E/ Test ( 339): Vlaue is Hell starts
E/ Test ( 339): Vlaue is Quit Monday

You can download the project for reference.



Siyanatullah Khan

Siyanatullah Khan

Mobile Software consultant with a penchant for blogging.

More Posts

Follow Me:
TwitterLinkedInGoogle Plus

Add a Comment

HTML Snippets Powered By :