Using a variable in getString()

3.1k Views Asked by At

I'm using a random number to pull a string from a resource xml, all of which have a similar beginning (they are named "quote" with a number after, so quote1, quote2, etc.

I'm trying to find a way to access them using getResources().getString() but I don't know how to pass that, since getString wants an int, I can't do something like

String quoteToGet="R.string.quote"+String.valueOf(randNum) 
//randNum is the random int generated

because quoteToGet is a string, getString(quoteToGet) doesn't work.

What else could I do to achieve this?

1

There are 1 best solutions below

3
On

With this method, you should get a resource by its name.

private String getResStringId(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }

Use like following:

String quoteToGet= getResStringId("quote"+String.valueOf(randNum));