cerealspiller
cerealspiller

Reputation: 1401

Use a string to access an Array

I am trying to get values from a string array defined in strings.xml by using a string variable.

For instance, I have two string arrays in strings.xml called "a_test_arrays" and "b_test_arrays"

In my code, I based on a random selection a string could be saved as either "a_test" or "b_test"

String test;
//Randomly determine value of test. test = "a_test" or test = "b_test"

String[] test_array;
//get the selected array and store it's contents in test_array
//test_array = test + "_arrays";

I've been trying to use resource identifiers, but I'm completely stumped.

Upvotes: 0

Views: 56

Answers (2)

Geobits
Geobits

Reputation: 22342

You can get the id of an array by name using getIdentifier():

String test = "a_test";
Resources res = getResources();
int resId = res.getIdentifier(test + "_arrays", "array", "my.package.name");
String[] test_array = res.getStringArray(resId);

Note you can use this for any type of resource, whether it's drawable, string, etc. Just make sure you change the second parameter from "array" to the appropriate type.

Upvotes: 3

Umer Farooq
Umer Farooq

Reputation: 7486

This should get the job done:

String[] test_array = getResources().getStringArray(R.array.a_test);

Hope this helps

Upvotes: 0

Related Questions