Reputation: 597
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!
Upvotes: 1
Views: 1869
Reputation: 597
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...
Upvotes: 2
Reputation: 20319
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);
}
Upvotes: 1