Android get all countries on array spinner

FilipeOS picture FilipeOS · Sep 3, 2013 · Viewed 29.3k times · Source

I've searched a lot but the stuff I found was a little confused.

I need to get the android country list and set default the user locale.

For example: I'm registering an user account and I need to insert the country, in that spinner will show all countries but by default will appear my default locale.

Right now I have:

private Spinner spCountry;
private String array_spinner[];

...

spCountry = (Spinner) findViewById(R.id.spCountry);

array_spinner = new String[1];
array_spinner[0] = "Portugal";

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_spinner);
spCountry.setAdapter(adapter);

Thank you all for the help!

Answer

sanusi picture sanusi · Mar 3, 2014

As for me, i iterate the available Locales and add each of the item into an arrayList. And of course i have to ignore duplicates, and empty strings. Here is my code:

 SortedSet<String> countries = new TreeSet<>();
 for (Locale locale : Locale.getAvailableLocales()) {
     if (!TextUtils.isEmpty(locale.getDisplayCountry())) {
          countries.add(locale.getDisplayCountry());
         }
        }

Spinner citizenship = (Spinner)findViewById(R.id.input_citizenship);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, getCountryListByLocale().toArray(new String[0]));
citizenship.setAdapter(adapter);