0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Doh! I had "string" instead of "array". simple mistakes = disastrous consequences. Thanks!
0

This should get the job done:

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

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.