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);
Fenil Patel
  • 1,528
  • 11
  • 28
Anthony
  • 51
  • 7

2 Answers2

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

Tenten Ponce
  • 2,436
  • 1
  • 13
  • 40
  • 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 – Anthony Dec 18 '17 at 07:16
  • I still want to pass the value using string name – Anthony Dec 18 '17 at 07:19
  • I've updated my answer. This question already existed, refer to my link on my second option answer. – Tenten Ponce Dec 18 '17 at 07:24
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);
frogatto
  • 28,539
  • 11
  • 83
  • 129