1

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);
bwoogie
  • 4,339
  • 12
  • 39
  • 72

1 Answers1

2

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.

EboMike
  • 76,846
  • 14
  • 164
  • 167
  • Upvoted - there are of course some occasions where a dynamic resource is required, and using getIdentifier can reduce maintenance too. Just remember to check whether the return value is 0. – David Snabel-Caunt May 14 '11 at 20:56