bwoogie
bwoogie

Reputation: 4427

Calling a Resource by a string?

Here's the setup. I have a spinner, and each item in the spinner is associated with their own StringArray. I want to streamline the process of loading the StringArray when an item is selected in the spinner without using a bunch of if statements for each item.

The StringArray has the same name as the spinner item's text

Drawn out it would look like this:

String cat = parent.getItemAtPosition(pos).toString(); //Selected Spinner item (Category)

...

String catStringArray = "R.array." + cat;
listdata = getResources().getStringArray(catArray);  //Get the StringArray

is there a way to do this correctly?

--Edit-- @EboMike

Your answer sent me on a hunt and ran into this which I'm now using:

Class res = R.array.class;
Field field = res.getField(selectedCategory);
int saId = field.getInt(null);
String[] myList = getResources().getStringArray(saId);

Upvotes: 1

Views: 472

Answers (1)

EboMike
EboMike

Reputation: 77752

That's not a great approach. It's slow. It'd be better to have an internal integer array with all the R.string IDs or something similar.

If you really insist on using a string-based approach, use Resources.getIdentifier(). It's technically not a big deal if you only do it once.

Upvotes: 2

Related Questions