1

I need to access resources in xml dynamically.

res=getResources();
plc=res.obtainTypedArray(R.array.id1);

I would like to do it in a loop => change id1 to id2, id3, ... ,id1000 and in that loop work with the items of that respective array. I can do it with single array but can't jump to another one. Any suggestion how I can do that? ObtainTypedArray expects integer only as a parameter.

Thank you!

Whitewall
  • 597
  • 1
  • 7
  • 18
  • 2
    This should help you http://stackoverflow.com/q/5406108/839527 – JProgrammer Feb 29 '12 at 00:22
  • Thank you, JProgrammer. I have gone through the post you have suggested many times but can't see how it can be useful to me. I have just started with java, I have used myriad of other languages before. Could you add a bit more of your wisdom for poor little me? ;-) Thank you in advance – Whitewall Feb 29 '12 at 00:49

2 Answers2

2

Here is the exact solution to my problem of calling the TypedArray from XML in code:

1) in XML create array that indexes data arrays

<array name="arrind">
    <item>@array/id1</item>
    <item>@array/id2</item>
    <item>@array/id3</item>
</array>

 <string-array name="id1">
    <item>...</item>
    <item>....</item>
    <item>...</item>
</string-array>

<string-array name="id2">
    ...
</string-array>

...

2) recall the array in the code

Resources res=getResources();
TypedArray index=res.obtainTypedArray(R.array.arrind); //call the index array

    for (int i = 0; i < n; i++) {
        int id=index.getResourceId(i,0); //get the index
        if (id != 0){
            String[] handle=new String[n];
            handle=res.getStringArray(id); //use the index to get the actual array
            String a=handle[0]; //Access items in your XML array
            String b=handle[1];
            c=...

        }
    }

Thanks for all your useful advice, Idecided not to use the Field approach but I am sure I will get there after I gain more experience! You can make this solution even better using 2D array but I have no use for it in my code...

Whitewall
  • 597
  • 1
  • 7
  • 18
1

The answer in the comment shows you exactly how to do it. Here is an example:

Lets assume you have integers named: id1, id2, id3, id4, ..., id10 you can access them and store them into an array with this:

int array[] = {1,2,3,4,5,6,7,8,9,10};
int value[10];

for ( i=0; i<10; i++){
   String fieldName = "id" + Integer.toString(array[i]);
   Field field = R.id.class.getField(fieldName);
   value[i] = field.getInt(null);
}
slayton
  • 20,123
  • 10
  • 60
  • 89
  • Thank you, brilliant! I have also found this post very useful: http://stackoverflow.com/questions/4326037/android-resource-array-of-arrays ... – Whitewall Feb 29 '12 at 12:23