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!

2
  • 2
    This should help you stackoverflow.com/q/5406108/839527 Commented Feb 29, 2012 at 0: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 Commented Feb 29, 2012 at 0:49

2 Answers 2

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...

Sign up to request clarification or add additional context in comments.

1 Comment

its a bit convoluted and hard to read but if it works it works
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);
}

1 Comment

Thank you, brilliant! I have also found this post very useful: stackoverflow.com/questions/4326037/… ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.