Android get all countries on array spinner

A helpful and customizable Country Picker for your needs.

Gradle

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.ekimual:country-picker-x:1.0.0'

Sample Usage:

/* Declare */
CountryPickerDialog countryPicker;

/* Name of your Custom JSON list */
int resourceId = getResources().getIdentifier("country_avail", "raw", getApplicationContext().getPackageName());

countryPicker = new CountryPickerDialog(MainActivity.this, new  CountryPickerCallbacks() {
      @Override
      public void onCountrySelected(Country country, int flagResId) {
            /* Get Country Name: country.getCountryName(context); */
            /* Call countryPicker.dismiss(); to prevent memory leaks */
      }

      /* Set to false if you want to disable Dial Code in the results and true if you want to show it 
         Set to zero if you don't have a custom JSON list of countries in your raw file otherwise use 
         resourceId for your customly available countries */
  }, false, 0);

countryPicker.show();

Reference https://android-arsenal.com/details/1/4390


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);

You can use

private static final String DEFAULT_LOCAL = "Portugal";

Then use it to set default selection as follows.

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

OUTPUT:

enter image description here

UPDATE: Create arrays.xml in res/values

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
        <item>Portugal</item>
    </string-array>

</resources>

Then use following in your activity to get all the countries.

array_spinner = getResources().getStringArray(R.array.country_arrays);