MrMinemeet MrMinemeet - 10 months ago 73
Android Question

Choose a random text from string.xml

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

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

maybe some suggestions?

Answer Source

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) {
        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"?>
    <string-array name="planets_array">

and then:

String[] planets = res.getStringArray(R.array.planets_array);
int randomNum = rand.nextInt(planets.size() - 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download