0

This is for Android, but I believe it's a general Java question, so I'm labelling it as such.

I'm trying to use reflection on R.array to get an array from the list. The arrays are named stringArraySubCategoryX where X is replaced with a number from 0 to 20. This is my code, but I ran into a problem:

Field subCatField = R.array.class.getField("stringArraySubCategory" + position);
subCatergorySpinner.setAdapter(ArrayAdapter.createFromResource(InfoActivity.this, subCatField.getInt(R.array), android.R.layout.simple_spinner_item));

The problem part is the subCatField.getInt(R.array) bit, which is supposed to return the resource int value of the selected array. But Field.getInt(arg)'s argument is an Object. I checked R.array, and that says public static final class array, but it seems that it's not accepted.

What am I doing wrong?

1 Answer 1

1
subCatField.getInt(null)

Is what you're looking for. Provided the stringArraySubCategoryX is static, of course.

However ... you state: "I'm trying to use reflection on R.array to get an array from the list."

How is that an int?

subCatField.get(null)

will return the static Object contained in the Field

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

3 Comments

Correct - if the array is static you don't need an instance of the class and pass null instead.
In answer to your own question: Android has an object called R that has static int variables that represent all your resources that aren't the code itself (localized strings, images, so on). The ints are named after the filename or xml name= of each resource. I have a string-array in my strings.xml, but the resource identifier in R is an int that Context.getResources(int) uses to get the resource itself. Eg. getResources(R.array.stringArraySubCategory7)
Ahhh. Gotcha. Thanks for explaining (I haven't done any android programming ... though I really should, just to be familiar with it)

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.