Android GridView - Sort - Ascending and Descending


Android GridView - Sort - Ascending and Descending Tutorial

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

Example 1 - Android GridView - Array - Sort Ascending/Descending

In this class we look at how to sort a gridview in both ascending and descending manner.

Project Structure

Here's our project structure:

Project Structure

1. Create Basic Activity Project

  1. First create a new project in android studio. Go to File --> New Project.

3. Our Layouts

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.

We add a GridView here.

<?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"
    tools:context="info.tutorialsloop.hp.arraysortgridview.MainActivity">

    <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="Array Sorting GridView"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/mySortBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="12dp"
        android:fontFamily="serif-monospace"
        android:text="Toggle Sort" />

    <GridView
        android:id="@+id/myGridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/mySortBtn"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/headerLabel"
        android:layout_marginTop="33dp" />

</RelativeLayout>

4. MainActivity.java

Here's our main activity.

package info.tutorialsloop.hp.arraysortgridview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MainActivity extends Activity {
    GridView gv;
    Button mySortButton;
    private String[] galaxies={"Sombrero", "Cartwheel", "Pinwheel", "StarBust","Whirlpool","Ring Nebular", "Own Nebular","Centaurus A", "Virgo Stellar Stream", "Canis Majos Overdensity"
            , "Mayall's Object", "Leo","Small Magellonic Cloud", "Large Magellonic Cloud","Milky Way","Whirlpool","Black Eye Galaxy","IC 1011","Messier 81", "Andromeda", "Messier 87"};

    private boolean sortAscending=true;
    private boolean unSorted=true;

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

        initializeGridView();

    }
    private void initializeGridView()
    {
        gv= findViewById(R.id.myGridView);
        gv.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,galaxies));
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, galaxies[i], Toast.LENGTH_SHORT).show();
            }
        });

        mySortButton=findViewById(R.id.mySortBtn);
        mySortButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sortData();
            }
        });
    }
    private void sortData()
    {
        List<String> galaxiesList= Arrays.asList(galaxies);

        if(unSorted) Collections.sort(galaxiesList);
        else Collections.reverse(galaxiesList);

        sortAscending=!sortAscending;
        unSorted=false;

        gv.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,galaxiesList));
    }
}

Example 2

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

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

Download

Resource Link
GitHub Browse Browse
GitHub Download Link Download

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