Android ListView - Sort Ascending and Descending..

November 25, 2017 Oclemy Android ListView 3 minutes, 8 seconds

Sorting is a common task in all types of applications. Especially the ability to sort in both ascending and descending manner.

This allows you to reach the specific item faster. Such that you don't have to scroll through all the items looking for a single item. This is basic sorting with already provided APIs.

ListVew Ascending

ListVew Descending

Let's go.

Gradle Scripts

Let's move to build.gradle.

build.gradle

All we need to do here is add the com.android.support:appcompat-v7 dependency.

Our MainActivity will be counting on it. Our Mainactivity will derive from AppCompatActivity which resides in this support library.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])

        compile 'com.android.support:appcompat-v7:25.2.0'
        testCompile 'junit:junit:4.12'
    }

LAYOUTS

Let's come create our layouts:

1. activity_main.xml

The only layout we are working.

This layout will get inflated into the MainActivity user interface. All we'll have here is a ListView with a sort button.

Both of them are wrappedn in a LinearLayout. Our root tag however is RelativeLayout.

    <?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:id="@+id/activity_main"
        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.simplelistviewsort.MainActivity">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ListView
                android:id="@+id/lv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                 />

            <Button
                android:text="Sort"
                android:layout_centerInParent="true"
                android:layout_width="381.0dp"
                android:layout_height="70dp"
                android:background="@color/colorAccent"
                android:padding="10dp"
                android:id="@+id/sortBtn"
                android:layout_marginRight="0.0dp" />

        </LinearLayout>
    </RelativeLayout>

JAVA CLASSES

We work with only one java class.

1. MainActivity.java

This is our MainActivity. It's the launcher activity. It gets executed first when the app is launched.

However it's the only method we have. What makes it an activity is the fact that we derive from android.support.v7.app.AppCompatActivity.

We'll have a method called fillSpacecrafts() which will populate an arraylist for us with data. That arraylist will then act as our data source.

We'll sort data using the Collections.sort() method. For ascending we'll simply reverse the ascending.

Let's go:

    package com.tutorials.hp.simplelistviewsort;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;

    import java.util.ArrayList;
    import java.util.Collections;

    public class MainActivity extends AppCompatActivity {
        //VIEWS
        private ListView lv;
        private Button sortBtn;

        //DATA
        private static ArrayList<String> spacecrafts =new ArrayList<>();
        private boolean ascending = true;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            this.initializeViews();
            this.fillSpacecrafts();

        }

        //INITIALIZE VIEWS
        private void initializeViews()
        {
            lv = (ListView) findViewById(R.id.lv);
            sortBtn = (Button) findViewById(R.id.sortBtn);

            sortBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sortData(ascending);
                    ascending = !ascending;
                }
            });
        }

        /*
         * SORT
         */
        private void sortData(boolean asc)
        {
            //SORT ARRAY ASCENDING AND DESCENDING
            if (asc)
            {
                Collections.sort(spacecrafts);
            }
            else
            {
                Collections.reverse(spacecrafts);
            }

            lv.setAdapter(new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,spacecrafts));

        }

        /*
        FILL SPACECRAFTS DATA
         */
        private void fillSpacecrafts() {

            spacecrafts.clear();
            spacecrafts.add("Kepler");
            spacecrafts.add("Casini");
            spacecrafts.add("Voyager");
            spacecrafts.add("New Horizon");
            spacecrafts.add("James Web");
            spacecrafts.add("Apollo 15");
            spacecrafts.add("WMAP");
            spacecrafts.add("Enterprise");
            spacecrafts.add("Spitzer");
            spacecrafts.add("Galileo");
            spacecrafts.add("Challenger");
            spacecrafts.add("Atlantis");
            spacecrafts.add("Apollo 19");
            spacecrafts.add("Huygens");
            spacecrafts.add("Hubble");
            spacecrafts.add("Juno");
            spacecrafts.add("Aries");
            spacecrafts.add("Columbia");

            lv.setAdapter(new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,spacecrafts));

        }

    }

Comments