Eclipse/Java - Values in R.string.* return int?

James Cadd picture James Cadd · Dec 31, 2009 · Viewed 42.4k times · Source

I thought I'd be classy and use the string.xml file to define some constant strings for things like exception messages. In strings.xml I hit Add, chose the "String" option (not 'String Array'), then gave it a name and value. I was surprised to see that this code doesn't work:

throw new Exception(R.string.MyExceptionMessage);

And that fails because R.string.MyExceptionMessage is actually of type int. I can verify that type by looking in R.java. What am I missing?

Answer

Christopher Orr picture Christopher Orr · Dec 31, 2009

Everything in the R class is a reference, hence it's just defined as an int.

If your code is running within — or has access to — an 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 to be translated and so don't strictly need to be defined in an Android resource .xml file, you could store the strings as constants in some sort of StringConstants interface. That way you can refer to the strings from within utility classes that may not have access to the Context.