How to create a copy of a currency in a country that is not related to ISO 3166, for example en_UK?

In my application, I get the default user standard using Locale.getDefault() , and then pass it to Currency.getInstance(Locale) . This basically works, but I started getting reports from users that show an IllegalArgumentException trace in the stack trace:

Called: java.lang.IllegalArgumentException: Unsupported ISO 3166 country: en_UK at java.util.Currency.getInstance (Currency.java:81) at org.

I was expecting Android to return only valid locales, but this is apparently not the case.

How do I handle such cases to make sure that I only get valid ISO 3166 locales? An easy way would be to handle this particular case, but I would prefer to use a general solution, if any.

Does anyone have any experience? Thanks.

+4
source share
3 answers

ISO 3166 The two-letter abbreviation for the UK is not UK , the correct identifier is GB . UK exists for compatibility (a mistake made in the past).

I was looking for other exceptions, but could not find them, so at the moment I'm just handling a 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); 
+6
source

Currency.getInstance(...) expects the locale of the form "en_US", however Locale.getDefault() does not always return the locale of this form.

To prevent crashes in your application, 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 find the best way to get the most suitable character or just let the user select it.

0
source
 String symbolLocale =""; int localeLength = mLocale.split("-").length; if (localeLength == 2) { symbolLocale = new Locale( mLocale.split("-", 2)[0], mLocale.split("-", 2)[1] ); } else if (localeLength == 3) { symbolLocale = new Locale( mLocale.split("-", 3)[0] + "-" + mLocale.split("-", 3)[1], mLocale.split("-", 3)[2] ); } symbolString = Currency.getInstance(symbolLocale).getSymbol(symbolLocale); 
0
source

Source: https://habr.com/ru/post/1445149/


All Articles