Android GridView - Array - Sort Ascending/Descending

September 10, 2017 Oclemy Android GridView, Java Array 5 minutes, 5 seconds

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

Tools Used These are the tools we used to create the project:

  1. Language : Java.

  2. Platform : Android.

  3. IDE : Android Studio.

  4. OS : Windows 8.1

Let's go.


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.

  2. Type the application name and choose the company name. New Project Dialog

  3. Choose minimum SDK. Choose minimum SDK

  4. Choose Empty activity. Choose Empty Activity

  5. Click Finish. Finish

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you've created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:


        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.


Generated Project Structure

AndroidStudio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

2. Build.Gradle

Our app level(app folder) build.gradle.

AndroidStudio allows us to add our application dependencies right here using compile statements.

So we add our dependencies here. You may use later versions of the dependencies.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "info.tutorialsloop.hp.arraysortgridview"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    testCompile 'junit:junit:4.12'
}

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed to direct java coding.

This is an example of declarative programming.

Advantages of Using XML over Java
No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It's easily maintanable as the user interface is decoupled from your Java logic.
3. It's easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:


(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

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

Best Regards, Oclemy.

Comments