vjdhama
vjdhama

Reputation: 5058

How to get id of a string array in string.xml if you have the array name

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?

Upvotes: 1

Views: 4626

Answers (5)

Apoorv
Apoorv

Reputation: 13520

You can use

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

to get String and

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

to get String array.

Upvotes: 0

Ahmad Arslan
Ahmad Arslan

Reputation: 4528

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

Upvotes: 0

FD_
FD_

Reputation: 12919

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);

Upvotes: 2

Devrim
Devrim

Reputation: 15533

You can use this:

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

For instance:

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

See docs.

Upvotes: 10

SMR
SMR

Reputation: 6736

try R.array.yourarray Hope it helps.

Upvotes: 0

Related Questions