Adv

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:

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



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )