Andrei Herford Andrei Herford - 2 years ago 64
Java Question

Locale.getDefault() returns unsuported / invalid Locale for Currency.getInstance

my app uses the following code to get the local currency:

Locale locale = Locale.getDefault()
java.util.Currency localCurrency = java.util.Currency.getInstance(locale);


This workes fine in all my tests and was never a problem before. Today I saw a CrashLog in the Google Play Developer Console: The app crashes with:

java.lang.IllegalArgumentException: Unsupported ISO 3166 country: es


I can easy reproduce this error when using
new Locale("es")
instead of
Locale.getDefault()
:

Locale locale = new Locale("es");
java.util.Currency localCurrency = java.util.Currency.getInstance(locale);


Actually the same exception is thrown no matter was language code I use, e.g. "en", "de", "fr", etc. Only when also the country code is specified everthing workes fine, e.g.
new Locale("es", "ES")


I have two problems with Exception:

1. Why is "es" not a valid locale? As fas as I understand Locale names are formed by a language code (lowercase), and an optional country code. Thus
es-ES
would be a valid locale but "es" should be as well, shouldn't it?

2. What can I do to avoid this problem? I use
Locale.getDefault()
all over the app to give the user locale currency, locale numberformat, etc. I would assume that the system always returns a valid Locale but this is obviously not the case. How can I make sure, that a valid locale is used?

Answer Source

You should pay attention to this :

http://docs.oracle.com/javase/7/docs/api/java/util/Currency.html#getInstance(java.util.Locale)

If you specify a language and no country there is no way the system can determine a currency.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download