Kotlin Android – Filtering using DropDown/Spinner

0
User Management System
Learn Kotlin, Retrofit, MVVM and MySQL using this all-in-one app. It is designed to be beginner friendly.

Filtering data in android is important. One way is that you can use a searchview, where the user types in the search keyword and then you filter. This is ideal if the keyword is of infinite options, and you are building something of a tiny search engine in your app. However sometimes you have a finite set of keywords and you want users to be able to filter only based on those terms. For example in the app we are creating, we are including filtering a set of cosmic bodies, based on their type e.g planets, stars, moons etc. This is the perfect scenario to use a dropdown or spinner.

In this article we will be listing several examples. But basically here is what you will learn from this tutorial:

  1. How to filter listview/gridview/recyclerview data based on a value from a spinner.
  2. Filtering data based on a category or tag.
  3. Working with adapters for listview,gridview and recyclerview.

Let's go.

We use either Java or Kotlin.

(a). Java Filter ListView using spinner

The first example examines how to filter listview using spinner.

  • MainActivity
  • activity_main
  • Result
  • Download

Here is our main activity:

package info.camposha.listviewdropdownspinnerjava;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity {

    ListView myListView;
    Spinner mySpinner;
    ArrayAdapter<CosmicBody> adapter;
    String[] categories={"All","Planets","Stars","Galaxies"};

    /*
    Initialize ListView and Spinner, set their adapters and listen to spinner itemSelection events
    */
    private void initializeViews() {

        mySpinner = findViewById(R.id.mySpinner);
        mySpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, categories));

        myListView = findViewById(R.id.myListView);
        myListView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getCosmicBodies()));



        //spinner selection events
        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long itemID) {
                if (position >= 0 && position < categories.length) {
                    getSelectedCategoryData(position);
                } else {
                    Toast.makeText(MainActivity.this, "Selected Category Does not Exist!", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
    /*
    Populate an arraylist that will act as our data source.
     */
    private ArrayList<CosmicBody> getCosmicBodies() {
        ArrayList<CosmicBody> data = new ArrayList<>();
        data.clear();

        data.add(new CosmicBody("Mercury", 1));
        data.add(new CosmicBody("UY Scuti", 1));
        data.add(new CosmicBody("Andromeda", 3));
        data.add(new CosmicBody("VV Cephei A", 2));
        data.add(new CosmicBody("IC 1011", 3));
        data.add(new CosmicBody("Sun", 2));
        data.add(new CosmicBody("Aldebaran", 2));
        data.add(new CosmicBody("Venus", 1));
        data.add(new CosmicBody("Malin 1", 3));
        data.add(new CosmicBody("Rigel", 2));
        data.add(new CosmicBody("Earth", 1));
        data.add(new CosmicBody("Whirlpool", 3));
        data.add(new CosmicBody("VY Canis Majoris", 2));
        data.add(new CosmicBody("Saturn", 1));
        data.add(new CosmicBody("Sombrero", 3));
        data.add(new CosmicBody("Betelgeuse", 2));
        data.add(new CosmicBody("Uranus", 1));
        data.add(new CosmicBody("Virgo Stellar Stream", 3));
        data.add(new CosmicBody("Epsillon Canis Majoris", 2));
        data.add(new CosmicBody("Jupiter", 1));
        data.add(new CosmicBody("VY Canis Majos", 2));
        data.add(new CosmicBody("Triangulum", 3));
        data.add(new CosmicBody("Cartwheel", 3));
        data.add(new CosmicBody("Antares", 2));
        data.add(new CosmicBody("Mayall's Object", 3));
        data.add(new CosmicBody("Proxima Centauri", 2));
        data.add(new CosmicBody("Black Eye", 3));
        data.add(new CosmicBody("Mars", 1));
        data.add(new CosmicBody("Sirius", 2));
        data.add(new CosmicBody("Centaurus A", 3));
        data.add(new CosmicBody("Pinwheel", 3));
        data.add(new CosmicBody("Small Magellonic Cloud", 3));
        data.add(new CosmicBody("Uranus", 1));
        data.add(new CosmicBody("Alpha Centauri", 2));
        data.add(new CosmicBody("Large Magellonic Cloud", 3));

        return data;
    }
    /*
    Get the selected category's cosmic bodies and bind to ListView
     */
    private void getSelectedCategoryData(int categoryID) {
        //arraylist to hold selected cosmic bodies
        ArrayList<CosmicBody> cosmicBodies = new ArrayList<>();
        if(categoryID == 0)
        {
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getCosmicBodies());
        }else{
            //filter by id
            for (CosmicBody cosmicBody : getCosmicBodies()) {
                if (cosmicBody.getCategoryId() == categoryID) {
                    cosmicBodies.add(cosmicBody);
                }
            }
            //instatiate adapter a
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, cosmicBodies);
        }
        //set the adapter to GridView
        myListView.setAdapter(adapter);
    }
    /*
    when activity is created, setContentView then initializeViews.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initializeViews();
    }
}
/*
Data Object class to represent a single Cosmic body. Class has default access modifier
 */
class CosmicBody {
    private String name;
    private int categoryID;

    public String getName() {
        return name;
    }

    public int getCategoryId() {
        return categoryID;
    }

    public CosmicBody(String name, int categoryID) {
        this.name = name;
        this.categoryID = categoryID;
    }

    @Override
    public String toString() {
        return name;
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="Cosmic Bodies"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_below="@id/headerLabel"
        android:layout_centerHorizontal="true"
        android:background="@android:drawable/editbox_dropdown_light_frame" />
    <ListView
        android:id="@+id/myListView"
        android:layout_below="@id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Here is what you get when you run this project.

Enter your email we instantly send you the download link of our latest version of this project.

 

(c). Kotlin Filter ListView using spinner

In the first tutorial we saw how to filter a listview using spinner. That example was written in Java. Now let's re-write in kotlin.

  • MainActivity.kt
  • activity_main.xml
  • Result
  • Download

Here is the main activity for the kotlin project:

package info.camposha.kotlinlistviewfilter

import android.os.Bundle
import android.view.View
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
   private var adapter: ArrayAdapter<CosmicBody>? = null
    var categories = arrayOf("All", "Planets", "Stars", "Galaxies")

    /*
    Initialize ListView and Spinner, set their adapters and listen to spinner itemSelection events
    */
    private fun initializeViews() {
        mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, categories)
        myListView.adapter = ArrayAdapter(
            this, android.R.layout.simple_list_item_1,
            cosmicBodies
        )
        //myListView.adapter=adapter


        //spinner selection events
        mySpinner.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                adapterView: AdapterView<*>?,
                view: View,
                position: Int,
                itemID: Long
            ) {
                if (position >= 0 && position < categories.size) {
                    getSelectedCategoryData(position)
                } else {
                    Toast.makeText(
                        this@MainActivity,
                        "Selected Category Does not Exist!",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }
    }

    /*
   Populate an arraylist that will act as our data source.
    */
    private val cosmicBodies: ArrayList<CosmicBody>
        get() {
            val data = ArrayList<CosmicBody>()
            data.add(CosmicBody("Mercury", 1))
            data.add(CosmicBody("UY Scuti", 1))
            data.add(CosmicBody("Andromeda", 3))
            data.add(CosmicBody("VV Cephei A", 2))
            data.add(CosmicBody("IC 1011", 3))
            data.add(CosmicBody("Sun", 2))
            data.add(CosmicBody("Aldebaran", 2))
            data.add(CosmicBody("Venus", 1))
            data.add(CosmicBody("Malin 1", 3))
            data.add(CosmicBody("Rigel", 2))
            data.add(CosmicBody("Earth", 1))
            data.add(CosmicBody("Whirlpool", 3))
            data.add(CosmicBody("VY Canis Majoris", 2))
            data.add(CosmicBody("Saturn", 1))
            data.add(CosmicBody("Sombrero", 3))
            data.add(CosmicBody("Betelgeuse", 2))
            data.add(CosmicBody("Uranus", 1))
            data.add(CosmicBody("Virgo Stellar Stream", 3))
            data.add(CosmicBody("Epsillon Canis Majoris", 2))
            data.add(CosmicBody("Jupiter", 1))
            data.add(CosmicBody("VY Canis Majos", 2))
            data.add(CosmicBody("Triangulum", 3))
            data.add(CosmicBody("Cartwheel", 3))
            data.add(CosmicBody("Antares", 2))
            data.add(CosmicBody("Mayall's Object", 3))
            data.add(CosmicBody("Proxima Centauri", 2))
            data.add(CosmicBody("Black Eye", 3))
            data.add(CosmicBody("Mars", 1))
            data.add(CosmicBody("Sirius", 2))
            data.add(CosmicBody("Centaurus A", 3))
            data.add(CosmicBody("Pinwheel", 3))
            data.add(CosmicBody("Small Magellonic Cloud", 3))
            data.add(CosmicBody("Uranus", 1))
            data.add(CosmicBody("Alpha Centauri", 2))
            data.add(CosmicBody("Large Magellonic Cloud", 3))
            return data
        }

    /*
   Get the selected category's cosmic bodies and bind to ListView
    */
    private fun getSelectedCategoryData(categoryID: Int) {
        //arraylist to hold selected cosmic bodies
        val data = ArrayList<CosmicBody>()
        adapter = if (categoryID == 0) {
            ArrayAdapter(
                this, android.R.layout.simple_list_item_1,
                cosmicBodies
            )

        } else {
            //filter by id
            for (cosmicBody in cosmicBodies) {
                if (cosmicBody.categoryId == categoryID) {
                    data.add(cosmicBody)
                }
            }
            //instatiate adapter a
            ArrayAdapter(this, android.R.layout.simple_list_item_1, data)
        }
        //set the adapter to GridView
        myListView!!.adapter = adapter
    }

    /*
    when activity is created, setContentView then initializeViews.
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initializeViews()
    }
}

/*
Data Object class to represent a single Cosmic body. Class has default access modifier
 */
class CosmicBody(private val name: String, val categoryId: Int) {

    override fun toString(): String {
        return name
    }
}

Here is the layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="Cosmic Bodies"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_below="@id/headerLabel"
        android:layout_centerHorizontal="true"
        android:background="@android:drawable/editbox_dropdown_light_frame" />
    <ListView
        android:id="@+id/myListView"
        android:layout_below="@id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Here is what you get when you run the project:

Enter your email we send you the download link:

 

Android MySQL Retrofit2 Multipart CRUD,Search,Pagination rating

When I was a 2nd year Software Engineering student, I buillt a now defunct online tool called Camposha(from Campus Share) using my then favorite language C#(ASP.NET) to compete OLX in my country(Kenya). The idea was to target campus students in Kenya. I got a few hundred signups but competing OLX proved too daunting. I decided to focus on my studies, learning other languages like Java,Python,Kotlin etc while meanwhile publishing tutorials at my YouTube Channel ProgrammingWizards TV which led to this site(camposha.info). Say hello or post me a suggestion: oclemmi@gmail.com . Follow me below; Github , and on my channel: ProgrammingWizards TV

We will be happy to hear your thoughts

Leave a reply

+ forty two = forty five

Reset Password
Compare items
  • Total (0)
Compare
0
Shopping cart