Android ListView → Android ListView – Sort Ascending and Descending – Camposha

Android ListView

Android ListView

Android ListView

Android ListView – Sort Ascending and Descending

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.

The Collections class

The Collections class comprises exclusively of static methods that operate on or return collections.

This class is a member of the Java Collections Framework.

It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.

Collections API Definition

The Collections class is a concrete class defined in the java.util package.

package java.util;

It derives from java.lang.Object.

public class Collections extends Object {..}

java.lang.Object
   ↳    java.util.Collections

It was added in android API level 1.

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 wrapped in a LinearLayout. Our root tag however is RelativeLayout. We’ll then specify the ListView which is our adapterview and assign it an ID.

We will aslo specify a button which when clicked will show will toggle our sort order. We’ve used a LinearLayout to place the button just below the ListView by setting the Orientation to Vertical.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        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.

Specify Imports

First we need to specify our imports using the import keyword. This will add additional classes that our custom class will be using.

For example we are able to derive from android.support.v7.app.AppCompatActivity given that we have added the android.support.v7.app.AppCompatAvtivity class.

We also add android.widget.ListView and android.widget.Button, the two widgets we will be using.

Furthermore we add ArrayList and Collections which are two classes from the java.util package.

    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;

Create and Activity

We do this by making our class derive from AppCompatActivity:

public class MainActivity extends AppCompatActivity {..}

Define Instance Fields

We define our instance fields, some of the initialized while some only declared.

        //VIEWS
        private ListView lv;
        private Button sortBtn;

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

Our instance fields include as you can see a ListView, a Button, an ArrayList and a boolean.

Generate our Data

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 then bind the arraylist to our listview using the setAdapter() method.

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

        }

Sort Data

To sort data we’ll use the sort() method defined in the java.util.Collections class.

It’s a static method that allows us sort data in an ascending manner.

Then we can reverse() the already sorted data to acheive the descending order.

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

        }

Let’s go:

Full Source Code

Here’s the full source code:

Result

ListVew Ascending

ListVew Descending

Best Regards.

Leave a Reply

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

Join Us
X