In my app, I get the user's default locale using Locale.getDefault()
and then pass that to Currency.getInstance(Locale)
. It mostly works, but I have started getting reports from users which show the following IllegalArgumentException
in the stack trace:
Caused by: java.lang.IllegalArgumentException: Unsupported ISO 3166 country: en_UK at java.util.Currency.getInstance(Currency.java:81) at org.
I expected Android to only return valid locales, but that is apparently not the case.
How do I handle such cases to make sure I only get valid ISO 3166 locales? The easy way will be to handle this special case, but I would rather use a generic solution if there is one.
Anyone have experience with this? Thanks.
The ISO 3166 two-letter abbreviation for the UK is not UK
, the correct id is GB
. UK
is there for compatibility reasons (a mistake made in the past).
I did look for other exeptions but did not find any, so for now i would just handle the special case.
Locale loc = new Locale("en","UK"); // test code
if(loc.getCountry().equals("UK")){
loc = new Locale(loc.getLanguage(), "GB");
}
Currency cur = Currency.getInstance(loc);
Currency.getInstance(...)
expects a locale of the form "en_US", however, Locale.getDefault()
does not always return a locale of this form.
To prevent crashes in your app, you can use something like this:
public static String getCurrencySymbol(){
String cursym;
try {
cursym = Currency.getInstance(Locale.getDefault()).getSymbol();
} catch (IllegalArgumentException e) {
cursym = "?"; // default symbol
}
return cursym;
}
You can try to figure out a better way to get the most appropriate symbol, or just let the user choose one.
Your users (with dev settings enabled) or testers have manually set a weird and invalid country. This bug occurred to us, but it turned out our testers had configured Appium to set the device locale to en-UK
:).
A regular user can not select en-UK or any other invalid locale.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With