0

Let say I have 2 arrays

Array1 = 1,2,3,4,5
Array2 = a,b,c,d,e
String[] array = getResources().getStringArray(R.array.Array1);

That's work fine. But I don't want to use the code above again with another line

String[] array = getResources().getStringArray(R.array.Array2);

How do I get the below lines to work if I had declared xxx as variable for array name

String xxx = Array1;
String[] array = getResources().getStringArray(R.array.xxx);

2 Answers 2

2

You can:

int xxx = R.array.Array1; //change to integer

String[] array = getResources().getStringArray(xxx); //pass the whole id

Instead of passing just the name of the resource, pass the whole ID (as integer).

If you still want to pass the name as string, you can:

String xxx = "Array1";
int resourceId = getResources().getIdentifier(xxx, "array", getPackageName());
String[] array = getResources().getStringArray(resourceId);

reference of the second option: https://stackoverflow.com/a/3476447/9038584

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

3 Comments

I understand your point to pass ID as integer. However, the xxx variable is a string declared from some other method. 'int xxx = R.array.Array1; //change to integer' This won't work
I still want to pass the value using string name
I've updated my answer. This question already existed, refer to my link on my second option answer.
2

A simple util method in your activity or service:

String[] getArray(int id) {
    return getResources().getStringArray(id);
}

Usage:

String[] array1 = getArray(R.array.array1);

Comments

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.