Understanding Android Spinners and Populating Them with (Adding) a Set of Items

Spinners in Android are like select dropdowns (HTML) of web development. Once tapped, it shows a list of options in a dropdown menu from which one can select a value. It is very simple to add it as a View in the Layout file (just as any other view like TextView or EditView):

<Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/country" />

Populating the Spinner with a Set of Choices for the User

The data used to populate the Spinner can come from various sources but must be provided through a SpinnerAdapter like an ArrayAdapter if the source is an array or a CursorAdapter for result sets from database queries. ArrayAdapter and CursorAdapter (or SimpleCursorAdapter) are indirect sub classes of SpinnerAdapter.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Let’s go through a couple of ways to provide the data through arrays first.

String Array Resource

In the string resource file located at res/values/strings.xml (or you could create a new one at res/values/filename.xml where filename can be anything arbitrary) add a string array.

<string-array name="country_array">
        <item>Australia</item>
        <item>Canada</item>
        <item>China</item>
        <item>India</item>
        <item>Sri Lanka</item>
        <item>United States</item>
</string-array>

In the Activity code, here’s how you’ll need to create an adapter from the array resource (created above) and pass it to the spinner object:

Spinner countryView = (Spinner) findViewById(R.id.country);

// Create an adapter from the string array resource and use
// android's inbuilt layout file simple_spinner_item
// that represents the default spinner in the UI
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.country_array, android.R.layout.simple_spinner_item);
// Set the layout to use for each dropdown item
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

countryView.setAdapter(adapter);

The createFromResource method allows us to create an ArrayAdapter from the string array resource. The third layout argument passed to the constructor call is basically how the spinner control will look like when a manual selection is made (or the default one is showing up). The setDropDownViewResource method is used to specify the layout file used to represent each item in the dropdown. We use the in-built simple_spinner_dropdown_item layout file provided by the android platform.

ArrayList or Array of Objects

We could pass on the data via an ArrayList or an array of objects (for example strings). Let’s see an example with ArrayList:

ArrayList<String> countries = new ArrayList<String>();
countries.add("Australia");
countries.add("Canada");
countries.add("China");
countries.add("India");
countries.add("Sri Lanka");
countries.add("United States");

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, countries);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

countryView.setAdapter(adapter);

Pretty simple and straightforward (if you read the previous section)!

Using SimpleCursorAdapter

Using a CursorAdapter like SimpleCursorAdapter we can make the choices in the dropdown menu available from a database query. For example here’s how we can show the first 10 contacts from our phone book (using Contacts Content Provider).

// Columns from DB to map into the view file
String[] fromColumns = {
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
};
// View IDs to map the columns (fetched above) into
int[] toViews = {
        android.R.id.text1
};

Cursor cursor = getContentResolver().query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null,
        null,
        null,
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC LIMIT 10"
);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(
        this, // context
        android.R.layout.simple_spinner_item, // layout file
        cursor, // DB cursor
        fromColumns, // data to bind to the UI
        toViews, // views that'll represent the data from `fromColumns`
        0
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// Create the list view and bind the adapter
countryView.setAdapter(adapter);

The comments in the code does a good job at explaining each and every portion. Basically we define the column we want from our contacts provider database table and the view ID to which we want to map that data to, in order to display in the user interface. Then we query the database using a Content Resolver and create our adapter that we bind to the Spinner view eventually.

Extras

Getting the selected value of a Spinner is really easy. The getSelectedItem() method on the view object returns the value as an object that can be converted to a string using the toString() method. So basically we do something like this:

// Spinner view object
Spinner countryView = (Spinner) findViewById(R.id.country);
// Spinner view value
String country = countryView.getSelectedItem().toString().trim();

Receiving an event when the user selects an item is also very simple. Just need to implement the AdapterView.OnItemSelectedListener interface with the corresponding onItemSelected method:

countryView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String country = parent.getItemAtPosition(position).toString();

        Toast.makeText(LoginActivity.this, country, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});

That’s all folks! I hope this article gives you a good understanding of how to work with Spinners, especially how to populate data in them using various approaches.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

9 thoughts on “Understanding Android Spinners and Populating Them with (Adding) a Set of Items”

    1. I think AdapterView.OnItemSelectedListener should help you with that ? I’ve also shown the sample code that shows how to grab the selected value/option. You can use that for all sorts of purposes like querying the DB with that value or some other operation.

  1. Hi, I have created 2 spinner . 1st is generated from strings.xml. 2nd one will generate from mysql databse on selection of 1st spinner. please help me how to fetch database on 1st spinner.

  2. can i change the R.layout.simple_list_item1 by custom layout file like R.layout.abc,where abc is my xml layout file

  3. This was a very good article to show us the basics of the Spinner. If you get back to this article, could you update this page with the issue of the spinner.OnItemSelectListener() running with the job is initialized? This was causing me an issue when implementing the Spinner by itself to pass information to a secondary Activity causing that activity to run on the initial startup.

Leave a Reply

Your email address will not be published. Required fields are marked *