Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Currency instance with non ISO 3166 country like en_UK?

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.

like image 842
codinguser Avatar asked Nov 09 '12 22:11

codinguser


3 Answers

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);
like image 115
Frank Avatar answered Nov 10 '22 04:11

Frank


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.

like image 33
lenooh Avatar answered Nov 10 '22 03:11

lenooh


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.

like image 1
Carsten Hagemann Avatar answered Nov 10 '22 02:11

Carsten Hagemann