Android GridView - Sort - Ascending and Descending

android data sorting

Lets see how to sort data in android java using Collections class.We shall sort ascending and descending in GridView when button is clicked.

Intro

  • We sort data in ascending and descending manner on button click.
  • GridView is the component we are using here.
  • We use Collections.sort() method passing in our data source and reversing it.
  • We've used Android Studio as our IDE.
  • The code is well commented for easier understanding.

Common Questions we answer

With this simple example we explore the following :

  • How o sort data in Java Android
  • Sort data ascending and descending manner.
  • How to bind arraylist data to gridview.
  • How to sort using Collections class in java.
  • How to reverse a Collection.
  • Using ArrayAdapter with GridView.
  • How to sort and reverse an arraylist in Java.
  • Using Android with GridView.

Tools Used

  • IDE : Android Studio
  • OS : Windows 8.1
  • PLATFORM : Android
  • LANGUAGE : Java

Let's start

1. Build.Gradle(App)**

  • Here's our app level build.gradle.
  • No external dependencies.

 

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.2.0'
    testCompile 'junit:junit:4.12'
}

     

2. MainActivity Class**

  • Our MainActivity,launcher activity.
  • First we reference views here.
  • Our adapterview is GridView.
  • We also have a button that shall get clicked.

 

package com.tutorials.hp.simplegridviewsort;

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

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

public class MainActivity extends AppCompatActivity {

    //VIEWS
    private GridView gv;
    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()
    {
        gv = (GridView) findViewById(R.id.gv);
        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);
        }

        gv.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");

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

    }

}

     

3. Main.axml Layout**

  • Main Layout.
  • We specify Views and widgets xml code here.
  • This layout shall get inflated into our MainActivity interface.
  • We have two components : GridView and Button.
  • GridView has two columns.

 

<?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.simplegridviewsort.MainActivity">

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

        <GridView
            android:id="@+id/gv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:numColumns="2" />

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

How To Run

  1. Download the project.
  2. You'll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.

More Resources

Resource Link
GitHub Browse Browse
GitHub Download Link Download

Oclemy,Cheers.

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

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post