Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

java - Retrieve a list of countries from the android OS

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 . . .

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...