Reputation: 4175
I have some country variable, "France" for example. I want to get the country code, in this example, I want to get "FR" or "fr".
I tried :
Locale locale = new Locale("", "FRANCE");
Log.e("test", locale.getCountry());
But it returns :
FRANCE
What I'm missing ?
Thank you !
Upvotes: 2
Views: 5419
Reputation: 1367
You could use the built-in Locale class:
Locale l = new Locale("", "CH");
System.out.println(l.getDisplayCountry());
prints "Switzerland" for example. Note that I have not provided a language.
So what you can do for the reverse lookup is build a map from the available countries:
public static void main(String[] args) throws InterruptedException {
Map<String, String> countries = new HashMap<>();
for (String iso : Locale.getISOCountries()) {
Locale l = new Locale("", iso);
countries.put(l.getDisplayCountry(), iso);
}
System.out.println(countries.get("Switzerland"));
System.out.println(countries.get("Andorra"));
System.out.println(countries.get("Japan"));
}
Answer found on this post. Hope it helps.
Upvotes: 3