How can I use name of string instead of content of string?

121 Views Asked by At

Normally, I use

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

So are there any ways to use

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

with NAME is string (String NAME = "name_array";)?

2

There are 2 best solutions below

0
On

Android replace string name to integer id after compile, but you place id to varialbe

int NAME = R.array.name_array;
String[] arrayName = getResources().getStringArray(NAME);
0
On

Going by what is in the official documentation, this is an acceptable way of referencing your array. However, I need to point out an error in your flow:

  • NAME must be an int. Therefore, the value should be R.id.name_array (this would return an int). Also, remove the double quotes around name_array.

You can do the referencing this way:

int NAME = R.array.name_array; // use a variable to store the int reference
String[] arrayName = getResources().getStringArray(NAME); //fetch