Reputation: 2509
I need to convert country iso3 code for example FRA to France is it possible? I tried with:
Locale locale = new Locale("FRA") or Locale locale = new Locale("","FRA")
locale.getDisplayCountry()
but return empty String.
Upvotes: 1
Views: 2915
Reputation: 236
In kotlin you can do below:
object CountryCodeConverter {
private val countryCodes: MutableList<CountryCode>
fun iso3CountryCodeToIso2CountryCode(iso3CountryCode: String?): String? {
return countryCodes.find { it.iso3CountryCode == iso3CountryCode }?.locale?.country
}
fun getCountry(iso3CountryCode: String?): String? {
return countryCodes.find { it.iso3CountryCode == iso3CountryCode }?.locale?.displayCountry
}
init {
countryCodes = ArrayList()
countryCodes.addAll(Locale.getISOCountries().map {country->
val locale = Locale("", country)
CountryCode(
locale.isO3Country.toUpperCase(),
locale
)
})
}
}
data class CountryCode (
val iso3CountryCode: String,
val locale: Locale
)
Upvotes: 1
Reputation: 4442
2nd parameter of Locale constructor needs a ISO2 code, not ISO3. You need to first map ISO3 to ISO2 and then get country name.
This possibly the worst case solution, I don't know any better solution, but its works.
String[] languages = Locale.getISOLanguages();
Map<String, Locale> localeMap = new HashMap<String, Locale>(languages.length);
for (String language : languages) {
Locale locale = new Locale(language);
localeMap.put(locale.getISO3Language(), locale);
}
Locale locale = new Locale("",localeMap("FRA"));
Log.e("loc",""+locale.getDisplayCountry());
Upvotes: 1