Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a resource name programmatically

Tags:

java

android

I have many string arrays in my resource files, and I want to access them programmatically depending on user input.

int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);

So if c==12, info should be the string-array with name "n_12". Is there a way to do this, and avoiding to do a switch statement with hundreds of cases?

Thanks

like image 948
leonsas Avatar asked Aug 09 '11 16:08

leonsas


2 Answers

If you want to get a resource by name (programmatically) and you are not sure how to address the resource by name (but you do know how to access it by R.), you can do this:

  • First print the exact resource name, like this:

Log.d("", context.getResources().getResourceName(R.id.whichYouAlreadyKnow) );

(Note: R.id.whichYouAlreadyKnow can be R.string.* R.drawable.* etc...)
Now you know the exact Resource address name

  • Take the printed name and use it as is, like this:

int id = getResources().getIdentifier(resource_name_that_printed_above, null, null);

Cheers

like image 94
Mercury Avatar answered Oct 25 '22 10:10

Mercury


You can get the resource id like so

int c = Getter.getCurrentNumber();
String resource = "n_" + c;
int id = getResources().getIdentifier(resource, "array", "com.your.project");

Then just use that id

String[] info = getResources().getStringArray(id);

Have a look here for another example on getResources().getIdentifier().

like image 28
Xavi Gil Avatar answered Oct 25 '22 10:10

Xavi Gil