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?
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).
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());
}
}
Albania
Algeria
Argentina
Australia
..
Venezuela
Vietnam
Yemen
# countries found: 95
Press any key to continue . . .