7

in my app I do a web request that returns some result code, e.g. 105. I have string resources that look like that

<string name="r105">O.K.</string>
<string name="r106">Something went wrong.</string>
<string name="r333">Fatal error.</string>

Now I want to do something like that

Toast.makeText(parent.getApplicationContext(),
        parent.getString(R.string.r+resultCode), Toast.LENGTH_LONG).show();

while r+resultCode is the resource identifier.

This does not work. Any idea how to do that?

2
  • In above code you used resource as r105 but, while accessing you written R.string.r Is it correct ?? Commented Dec 29, 2011 at 13:06
  • Now I understood your question, i will try give me 5 min. Commented Dec 29, 2011 at 13:17

3 Answers 3

16

Try this getResources().getIdentifier(name, defType, defPackage) in a simple way.

Toast.makeText(this, getResources().getIdentifier("r"+resultcode, "string", 
getPackageName()), Toast.LENGTH_LONG).show();
Sign up to request clarification or add additional context in comments.

Comments

4

You can do it using getResources().getIdentifier(name, defType, defPackage). Something like this:

// Assuming resultCode is an int, use %s for String
int id = getResources().getIdentifier(String.format("r%d", resultCode), 
                                      "string", getPackageName());
String result = getString(id);

1 Comment

Ah, I thought resultCode was an int. Try %s for string or just do "r"+resultCode.
-1

Try as below, its working for me. Use parent.getApplicationContext() for you.

String str = getString(R.string.r)+resultCode;

        Toast.makeText(getApplicationContext(),
                str, Toast.LENGTH_LONG).show();

3 Comments

I think getString(R.string.r)+resultCode wont work because there is no resource called "r"
I given part of my code only, not entire thing. I used it in my project in xml file.
I have updated my question, no it is not working because R.string.r fails, there is no resource r

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.