-1

I have a string.xml file full of text_1 ... text_100 Now I want to choose a random text of these and display it on a TextView. I tried to use

String text = "text_";
int randomNum = rand.nextInt((100 + 1) + 1;
text = text + String.valueOf(randomNum);
txt.setText(getString(R.string.text);

so now it doesn't work because there is no "text" in the string file...

maybe some suggestions?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
MrMinemeet
  • 304
  • 6
  • 17

2 Answers2

0

You can use this, but it is bad practise:

public static int getResId(String resName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(resName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

In your case:

getResId(text, String.class);

Better option is to create array of strings in xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

and then:

String[] planets = res.getStringArray(R.array.planets_array);
int randomNum = rand.nextInt(planets.size() - 1);
txt.setText(planets[randomNum]);
mac229
  • 4,319
  • 5
  • 18
  • 24
0

You don't just come up with an int id like that. Since you know the resource name, use this method of Resources.class : getIdentifier(resIdName, resTypeName, packageName)

As Resources belongs to Context, you do:

String text = "text_";
 int randomNum = rand.nextInt((100 + 1) + 1; 
text = text + String.valueOf(randomNum);
int textId = getResources().getIdentifier(text, "string", getPackageName());
txt.setText(getString(textId));

There you have the resource id of the item in your string resource.

It was answered here

Francis Nduba Numbi
  • 2,499
  • 1
  • 11
  • 22