1

I there a simple way to get the id of the string array defined in string.xml using it's string name? I have a string name of the string array, i need a way to reference that array. Below is the just an sample xml.

<string-array name="categories_array">
    <item>Clothes</item>
    <item>Electronics</item>
    <item>Gifts</item>
    <item>Food</item>
</string-array>
<string-array name="clothes">
    <item>Clothes</item>
    <item>Electronics</item>
    <item>Gifts</item>
    <item>Food</item>
    <item>Books</item>
    <item>Music</item>
    <item>Bags</item>
</string-array>
<string-array name="electronics">
    <item>Clothes</item>
    <item>Electronics</item>
    <item>Gifts</item>
    <item>Food</item>
    <item>Books</item>
    <item>Music</item>
    <item>Bags</item>
</string-array>
<string-array name="gifts">
    <item>Clothes</item>
    <item>Electronics</item>
    <item>Gifts</item>
    <item>Food</item>
    <item>Books</item>
    <item>Music</item>
    <item>Bags</item>
</string-array>
<string-array name="food">
    <item>Clothes</item>
    <item>Electronics</item>
    <item>Gifts</item>
    <item>Food</item>
    <item>Books</item>
    <item>Music</item>
    <item>Bags</item>
</string-array>

Now if i have the array name "clothes" , how would i get it's id?

1
  • 1
    can you describe better with an example? Commented Feb 17, 2014 at 12:55

5 Answers 5

10

You can use this:

int resId = getResources().getIdentifier("nameOfStringResource", "array", getPackageName());

For instance:

int resId = getResources().getIdentifier("categories_array", "array", getPackageName());

See docs.

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

Comments

2

This can be done using reflection:

String name = "your_array";
final Field field = R.array.getField(name);
int id = field.getInt(null);
String[] strings = getResources().getStringArray(id);

Or using Resources.getIdentifier():

String name = "your_array";
int id = getResources().getIdentifier(name, "array", getPackageName());
String[] strings = getResources().getStringArray(id);

Comments

0

try R.array.yourarray Hope it helps.

Comments

0
String[] some_array = getResources().getStringArray(R.array.categories_array);

Comments

0

You can use

getResources().getString(R.string.your_string)

to get String and

getResources().getStringArray(R.array.your_string)

to get String array.

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.