0

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;
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Shawn.Y
  • 181
  • 3
  • 14

1 Answers1

8

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;  
}
Shashank Mishra
  • 542
  • 4
  • 12
  • Dont really understand what is the purpose for using HashMap in this code? – Shawn.Y Jun 01 '18 at 08:27
  • Actually, HashMap Was For Storing All The Codes With Country Names As Key, Something Like This -> , But Now I Have Edited The Code As Per Your Requirement. – Shashank Mishra Jun 01 '18 at 08:34