Eclipse / Java - values ​​in R.string. * Return int?

I thought I would be cool and use the string.xml file to define some constant lines for things like exception messages. In strings.xml, I click Add, selects the String parameter (not the String Array), and then gives it a name and value. I was surprised to see that this code does not work:

throw new Exception(R.string.MyExceptionMessage); 

And this does not work, because R.string.MyExceptionMessage is of type int. I can check this type by looking in R.java. What am I missing?

+50
java android string resources
Dec 31 '09 at 1:42
source share
3 answers

Everything in class R is a reference, so it is simply defined as int .

If your code runs in - or has access to - Android Context , you can call context.getString(R.string.my_exception_message) to get the actual String value.

Or for things like exception strings that don't require translation and therefore don't have to be defined in the Android XML file, you can store strings as constants in some StringConstants interface. Thus, you can refer to strings from utility classes that may not have access to Context .

+97
Dec 31 '09 at 1:49
source share

Use the getResources () method. getString (id).

  getResources().getString(R.string.title_activity) 

And boom, you have your line. Be sure to save this string in the string.xml file in the values ​​folder.

+29
Feb 10 '13 at 19:09
source share
Chris is right. But what if you want to also localize the Exception string. For example, you throw an exception, and when you catch it, you want to display an exception message to the user. I would like to put them in strings.xml, but at the same time I do not want to use this code
 throw new Exception(context.getString(R.string.my_exception_message)) 

because I think that if you have an exception, you probably don’t want to, and you cannot use additional code to receive the exception message.

I think the only solution would be to declare a static String for this message in your main Office and initialize it as soon as possible (for example, in the onCreate () method):

 private static String my_exception_message; public onCreate() { my_exception_message = context.getString(R.string.my_exception_message); } 

Therefore, when you throw an exception, you have a localized message ready to use it. What do you think? Can you think of some other solutions?

+5
Mar 30 '11 at 11:05
source share



All Articles