Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

How to use a String as a part of a call

+13 votes

So I have a deck of cards, and each card I can get the number with a getNumber() method.  I have strings for rules for each card number, like "default_ace" in strings.xml.  Every time a card is drawn, I can parse everything correctly, but I need a way to set the text of a textView to the rule I have in strings.xml, depending on the card that is drawn.

String cardName = "default_" + card.getNumber().toString();  // makes the exact string name in strings.xml

This last line obviously does not work because "cardName" is not the name of a String Name in strings.xml.  I want the value of the String cardName to be used.

asked Apr 17, 2015 in Spring 2015 by Christian Schroeder (100 points)
edited Apr 17, 2015 by Christian Schroeder

3 Answers

+5 votes
Best answer
int identifier = getResources().getIdentifier (cardName,"string", YourClass.this.getClass().getPackage().getName());
if (identifier!=0){

I think this will work.

answered Apr 17, 2015 by Ethan Wojcinski (100 points)
edited Apr 17, 2015 by Ethan Wojcinski
instead of "your.package.name.here" use YourActivity.this.getPackageName()
That works!!!

String cardName = "default_"+ card.getNumber().toString().toLowerCase();
                int identifier = getResources().getIdentifier(cardName, "string", GameFragment.this.getClass().getPackage().getName());
                if (identifier !=0){
+5 votes

Hmm... it seems to me that what you should *really* be using is a String ARRAY resource, rather than individual strings.  (See the sample FlagQuiz app in our book for example usage...)

answered Apr 19, 2015 by Forrest Stonedahl (3,438 points)
Good point! I may end up going this route, since the card rules change, and the array would be easier to change, and then keep default rules in the strings.xml.
+2 votes

I think this line might work, this should return a string instead of returning an integer. Let me know what happens when you use this, I have some other ideas that might work if this does not.

answered Apr 17, 2015 by Ethan Wojcinski (100 points)
Unfortunately that does not work...it still is looking for a string name from strings.xml