Android Simple Spinner - Fill with List Of Objects


Hello guys.How do you do? This is what we do:

  1. Populate ArrayList with Person objects.
  2. Pass this ArrayList to our ArrayAdapter.
  3. Set our adapter to our Spinner
  4. Handle ItemSelection events,hence show a toast.

Demo

Here is the demo of this project.

Project Demo

First things first, let's start by some introductions.

API Reference - Important APIs to Know First

Here are the API's we've used for this project.

Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time.

Android Spinner

Spinner is an AdapterView. This means that it relies on an Adapter for its data.

Adapters act as the bridge between adapterviews and the underlying data source.

This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.

Spinner is a concrete public class residing in the android.widget package.

package android.widget;

Spinner is a public class that's why we can access and use it.

public class Spinner{}

Public classes are visible even from other packages apart from those they've been defined.

Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.

AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.

We can use the Spinner object to specify the spinner in an xml Layout. This pattern of specifyng an Object in the Layout resource then referencing from the Java/Kotlin code is common in android as a platform and is also the one recommended.

Here are some of it's advantages:

No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It's easily maintanable as the user interface is decoupled from your Java logic.
3. It's easier to share or download code and safely test them before runtime.
4. You can use XML generation tools to generate XML as an alternative to Android Studio.
<Spinner
    android:id="@+id/mySpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

2. How to Import Spinner

First we imported Spinner from it's android.widget pakage:

import android.widget.Spinner;

3. How to Reference spinner from Layout

Then referenced using the findViewById() of the Activity class:

Spinner sp= (Spinner) findViewById(R.id.sp); 
(b). List - an Interface

In Java List is an interface representing an ordered collection (also known as a sequence).

As an interface you cannot directly instantiate List<E>, instead it is there to be implemented by classes, which may then be instantiated.

And infact many important classes like the ArrayList either directly or indirectly implement this interface.

Then those implementers get precise control over which position an element is inserted. Afterwards you can access elements by their integer index (position in the list), and also search for elements in the list.

Lists can allow duplicate elements. If you don't want duplicates then it is recommended you use Set.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

2. How to use a java List

We use it and it's implementer the ArrayList to hold our list of person Objects.

We've instantiated it and passed

        List<String> people=new ArrayList<>(); 

Then cleared it:

            people.clear();

and used the add() method to add Person objects:

            Person p=new Person(); 
            p.setName("Mike"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("John"); 
           ....
(c). ArrayAdapter - an Adapter

We will use an ArrayAdapter instance to bind our data to our spinner.

2. How to Instantiate an ArrayAdapter

You pass:

  1. The Context
  2. The Resource
  3. The List
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,people); 

3. How to Bind Set an ArrayAdapter to a Spinner

You use the setAdapter() method.

        sp.setAdapter(adapter); 

Full Code

Let's now look at the full source code.

Our Person Class

  • Is our data object.
  • Represents a single person with his properties.
package com.tutorials.hp.spinnerandobjects;

public class Person {

    int id;
    String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

SECTION 2 : Our MainActivity

Our main activity class.

package com.tutorials.hp.spinnerandobjects;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity { 
    List<String> people=new ArrayList<>(); 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        //SPINNER 
        Spinner sp= (Spinner) findViewById(R.id.sp); 
        //FILL LIST 
        fillPeople(); 
        //ADAPTER 
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,people); 
        sp.setAdapter(adapter); 
        //item selected 
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override 
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
            Toast.makeText(MainActivity.this, people.get(i), Toast.LENGTH_SHORT).show(); }
             @Override 
             public void onNothingSelected(AdapterView<?> adapterView) {

              } 
            }); 
        } 
        private void fillPeople() { 
            people.clear(); 
            Person p=new Person(); 
            p.setName("Mike"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("John"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("Lucy"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("Rebecca"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("Kris"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("Kurt"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("Vin"); 
            people.add(p.getName());
            }
}

Resoources.

Android platform provides a powerful and flexible way of adding static content as a resource.

These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.

Resources belong to a given type. These types can be:

  1. Drawable.
  2. Layout.
  3. Value.

Let's start by looking at the layout resources

(a). activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorials.hp.simplespinner.MainActivity">

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

SECTION 4 : Source Code Reference

GitHub : Source

Best Regards,

Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post