Retrieve a list of countries from the android OS

user1187383 picture user1187383 · Mar 18, 2012 · Viewed 44.5k times · Source

I'm looking for a way to populate a spinner with a list of countries with their names. Can I retrieve it from the Android OS? Can someone please provide me an example?

Answer

Andrew Thompson picture Andrew Thompson · Mar 18, 2012

You might get some idea from the Locale class.

Call getAvailableLocales() then iterate the array & getDisplayCountry(). If it is the first time you've seen that country name, add it to an expandable list (e.g. an ArrayList instance).


E.G.

In Java, but the 3 classes from java.util are all available in Android.

import java.util.*;

class Countries {

    public static void main(String[] args) {
        Locale[] locales = Locale.getAvailableLocales();
        ArrayList<String> countries = new ArrayList<String>();
        for (Locale locale : locales) {
            String country = locale.getDisplayCountry();
            if (country.trim().length()>0 && !countries.contains(country)) {
                countries.add(country);
            }
        }
        Collections.sort(countries);
        for (String country : countries) {
            System.out.println(country);
        }
        System.out.println( "# countries found: " + countries.size());
    }
}

Output on this desktop PC

Albania
Algeria
Argentina
Australia
..
Venezuela
Vietnam
Yemen
# countries found: 95
Press any key to continue . . .