Search code examples
androidlocalecountry-codes

Converting a country name to ISO Alpha 2 country code


I am using the country code picker library for user to select a country.
I stored the selected items with country name (i.e.: Singapore).
Now I want to convert the country name into ISO Alpha 2 country code (i.e.: sg).

I am using the Locale but it was not working, what am i missing?

public String getCountryCodeFromName(String countryName){
    Locale locale = new Locale("",countryName);
    String countryCode = locale.getCountry().toLowerCase();
    return countryCode;
}

Solution

  • Use This Function:-

    public String getCountryCode(String countryName) {
    
        // Get all country codes in a string array.
        String[] isoCountryCodes = Locale.getISOCountries();
        String countryCode = "";
        // Iterate through all country codes:
        for (String code : isoCountryCodes) {
            // Create a locale using each country code
            Locale locale = new Locale("", code);
            // Get country name for each code.
            String name = locale.getDisplayCountry();
            if(name.equals(countryName))
              {
                 countryCode = code;
                 break;
              }
        }
        return countryCode;  
    }