Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get country code from country name in android

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?

like image 742
Tristus Avatar asked Feb 13 '15 15:02

Tristus


People also ask

How can I get country code in Android?

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.

How do you find a country's country code?

Locale loc = new Locale("NL"); loc. getCountry();

What is locale Android?

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.


1 Answers

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.

like image 91
Vlad Avatar answered Oct 05 '22 00:10

Vlad