-2

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?

MikeKeepsOnShine
  • 1,730
  • 4
  • 23
  • 35
Jordan P
  • 19
  • 1
  • 4

1 Answers1

0

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));
MikeKeepsOnShine
  • 1,730
  • 4
  • 23
  • 35
  • 1
    i just love reputation's farmers ... it just a copy from http://stackoverflow.com/questions/7493287/android-how-do-i-get-string-from-resources-using-its-name#answer-11595723 – Selvin Jun 19 '15 at 15:00
  • 1
    oh, i'm sorry, i used this method for an application at least one year ago, and yes, probably i found that method on stackoverflow in that question. I don't try to increase my reputation with brutal copy/paste from another answers. – MikeKeepsOnShine Jun 19 '15 at 15:08
  • You need to add attribution to your answer to the original answer. – Bill Woodger Aug 12 '15 at 16:49