1

So I'm going to make my application Multilingual and making different String.xml's for different languages. I'm also changing my texts, such as

String message = "Calling " + name;
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, message, duration);
                toast.show();

to

String message = toastCalling + name;

(From strings.xml)

<string name="toastCalling">Calling</string>

I'm facing a problem, that it apparently is an INT, and either cannot be resolved, or changes the value of toastCalling (Calling) to "278172" (Random Numbers)

Is there a way to get the ACTUAL value of R.String.toastCalling (Calling)

I have tried:

String whatever = getResources().getString(R.string.toastCalling);

But I don't think that's practical.

Thanks in advance!

5
  • 2
    You may not think it's practical, but that's how you're supposed to do it. Commented Dec 18, 2013 at 12:41
  • 1
    you can usually just call getString(R.string.blabla); but yeah that's the way you're supposed to do it and it's not that inconvenient ;) Commented Dec 18, 2013 at 12:42
  • @TomG But, Let's say the Phone's language is Spanish. It will be checking for string-es.xml. How is "getResources().getString(R.string.toastCalling);" going to get the SPANISH Xml? Commented Dec 18, 2013 at 12:43
  • 1
    Because getResources() is going to automatically point to the correct resource bundle for the current Locale. Commented Dec 18, 2013 at 12:46
  • @TomG Ah, if getResources() can get that automatically, there won't be a single problem. I was just having my doubts since there will be a language change as well. Thank you for your answers/comments! Commented Dec 18, 2013 at 12:47

1 Answer 1

5

If you're within the activity's scope, you can and are supposed to call getString(R.string.toastCalling); to receive the string. If you're not in the activity's scope, you need getResources, as in your example. This is how it is supposed to be done.

By the way, your three lines for the toast can be shortened into one: Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, Thank you. I have the shortened code as well. But I keep it a bit longer, "Easier" for the other people that work on this project as well. :). I will be using getString();. Thank you! (Can accept in 11 minutes)

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.