I know there is a way to obtain the country name from a country code, but is it also possible the other way arround? I have found so far no function that converts a String like "Netherlands" into "NL". If possible, how can I obtain the country codes?
Android App Development for BeginnersStep 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken a text view to show the current country code.
Locale loc = new Locale("NL"); loc. getCountry();
With Locale®, you create situations specifying conditions under which your phone's settings should change. For example, your "At Work" situation notices when your Location condition is "77 Massachusetts Ave.," and changes your Volume setting to vibrate.
public String getCountryCode(String countryName) {
// Get all country codes in a string array.
String[] isoCountryCodes = Locale.getISOCountries();
Map<String, String> countryMap = new HashMap<>();
Locale locale;
String name;
// Iterate through all country codes:
for (String code : isoCountryCodes) {
// Create a locale using each country code
locale = new Locale("", code);
// Get country name for each code.
name = locale.getDisplayCountry();
// Map all country names and codes in key - value pairs.
countryMap.put(name, code);
}
// Return the country code for the given country name using the map.
// Here you will need some validation or better yet
// a list of countries to give to user to choose from.
return countryMap.get(countryName); // "NL" for Netherlands.
}
Or a Kotlin one liner:
fun getCountryCode(countryName: String) =
Locale.getISOCountries().find { Locale("", it).displayCountry == countryName }
As noted in the comments, if you're using Java, depending on how often you call this method, you might want to pull the map out of it but better yet look at the optimised version by @Dambo without the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With