Get all string resources from XML resource file?

2.6k views Asked by At

I have a resource file called suggestions.xml which is translated to a couple of languages. These XML files contain just <string> values.

Now, I'd like to retrieve all the strings in the current locale's suggestions.xml file. How do I do that? I know I can retrieve single strings by their ID's, but I'd like to get all the strings in the XML file instead.

2

There are 2 answers

2
Sharp Edge On

You can declare your strings like this.

 <string-array name="fruitcategory_array">

    <item>Apple</item>
    <item>Bananas</item>
    <item>Mangoes</item>
    <item>Grapes</item>
    <item>Other</item>

 </string-array>

In your activity class, you can access them like the following.

String[] categories;

categories=getResources().getStringArray(R.array.fruitcategory_array);

Just store your Local Strings in an Array in your suggestions.xml file.

3
Vesko On

I wonder why would you need to do this. Still, you can use the generated R class to iterate over all kinds of resources.

Field[] fields = R.string.class.getFields();
String[] stringNames = new String[fields.length];
for (int  i = 0; i < fields.length; i++) {           
    stringNames[i] = fields[i].getName();
}