Acquiring a country's currency code

这一生的挚爱 提交于 2019-11-30 09:01:20

问题


I have a problem getting a country's currency code. My task is to get the user's location, find out what country he is right now and get this country's currency code. Here's the code that fetches the country name and country code from the acquired location:

Geocoder gc = new Geocoder(this);
List<Address> addresses = gc.getFromLocation(
                location.getLatitude(), location.getLongitude(), 5);

textView1.setText(addresses.get(0).getCountryName());
textView2.setText(addresses.get(0).getCountryCode());

This works perfectly fine. Now I should use the java.util.Currency class to get a Currency object. I can use the Currency.getInstance(Locale locale) method. But there's no constructor in the Locale class that allows only the country code to be passed as an argument. Means I am not able to create a Locale object for the country. How can this be solved? Thanks in advance.


回答1:


You should be able to use Currency.getInstance(new Locale("",code)), with a possible Exception if the country code isn't valid.




回答2:


String lang = Locale.getDefault().getDisplayLanguage();
Locale locale = new Locale(lang, COUNTRY_YOU_HAVE);



回答3:


Why not you use Address object to get Locale, by method:

http://developer.android.com/reference/android/location/Address.html#getLocale%28%29




回答4:


Keep in mind that the result of doing this will be inaccurate since we don't have the Language Code, or it can even throw an exception due to not having that Locale on the system. Instead I'd search for it doing the following:

val locale = Locale.getAvailableLocales().first { it.country == address.countryCode }
val currency = Currency.getInstance(locale)

Also, if you want to try to be as accurate as possible, you could do this:

val locale =
    Locale.getAvailableLocales().firstOrNull { it.country.equals(countryCode, true) && it.language.equals(countryCode, true) }
        ?: Locale.getAvailableLocales().firstOrNull { it.country.equals(countryCode, true) }
        ?: Locale.getDefault()
val currency = Currency.getInstance(locale)


来源:https://stackoverflow.com/questions/9158428/acquiring-a-countrys-currency-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!