Android studio list сортировка

Android ListView Sorting Examples

When you have a collection of data, one of the most important feature to add is the ability to sort that data. In this piece we will look at all data sorting examples related to listview and gridview.

Example 1: Android Arrays – Sort Descending and Ascending Order

This is an android data sorting tutorial. How to sort in both ascending and descending manner.

We all know Java provides us the java.util.Collection framework for manipulating data including sorting.

With this we can sort any collection. However, an array is a built language feature and is not found in java.util.Collection .

However we have the Array class which provides us with the asList method that we can use to convert our Array into a List then sort it via the Collections API.

We can then call the Collections.sort() passing in our List. This sorts the data in ascending order by default.

We can then reverse it into descending, which is the opposite of ascending:

1. Create Project

  1. First create an empty project in Android Studio. Go to File –> New Project.
  2. Type the application name and choose the company name.
  3. Choose minimum SDK.
  4. Choose Empty activity.
  5. Click Finish.

This will generate for us a project with the following:

  • 1 Activity – MainActivity.java
  • 1 Layout – activity_main.xml .

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 . as following, replacing the MainActivity with your activity name:

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.

Project Structure

Here’s our project structure.

Layouts

We’ll have only one layout, our activity_main.xml . We are working with:

Here’s the component tree:

Here’s our design pallete:

Here’s our XML Layout, our activity_main.xml file:

Java Code

We’ll have only one class the MainActivity .

First we specify the package name:

Then create the class

Let’s add the imports we’ll use:

We then make the class derive from Activity.

Our class will have the following instance fields. Instance fields are private properties of a class.

  • The ListView is our adapterview onto which we’ll bind data.
  • The button will toggle between ascending and descending order.
  • The galaxies is a String array that will act as our data source.
  • Then sortAscending is also a boolean that will maintain for us the state of sorting whether ascending or descending.
  • The unsorted will help us determine the first time the user has clicked the sort button so that we can sort only once then subsequently only reverse instead of resorting every time the user clicks the sort button.

We’ll the create an initializeViews() method to initialize our views.

In the above we reference the ListView from our XML layout using the findViewById() . This method is defined in the android.app.Activity class from which our MainActivity derives. We then call the ListView’s setAdapter() method. And pass it an instance of an ArrayAdapter.

Our ArrayAdapter takes the following parameters:

  • Context object.
  • TextView resource
  • Data Source

We also reference the button from the XML layout. And invoke it’s setOnClickListener event handler.
Then call sortData() inside it. We’ll define this method next.

Читайте также:  Лимит передачи данных андроид что это такое

Then sortData() method:

This method will be responsible for sorting our data in both ascending and descending.

First we convert our Array to an ArrayList using the asList() method, passing in the array as a parameter. This gives us a List object which is passable to a collection to be sorted.

We check if our unSorted boolean is set to true. If so then we sort the data using the Collection’s sort() method, passing in our List object.

If it’s false then we simply reverse the Collection using the reverse() method.

We then toggle sortAscending to its negation, then update the unSorted to false.

After that we set our adapter to our ListView. This time however we pass our sorted List object as the data source.

Let’s now come to the last part of our MainActivity class.

The OnCreate() method.

This method is one of lifecycle methods for android. This means it get’s called at a particular time in the lifetime of an activity. In this case after the creation.

It’s a method we are overriding. This means it has already been defined in the parent class. The parent class of our MainActivity is android.app.Activity .

The first requirement when overriding a lifecycle method is to invoke the onCreate() method that’s defined inside that parent class. So we call super.onCreate() .

And we pass it a Bundle object. A Bundle is a class that allows us map string values to parceable types. It’s a class belonging to android.os package and deriving from android.os.BaseBundle .

After that we call the setContentView() passing in our layout. This method belongs to our Activity. it knows and will inflate our XML layout into an android.view.View object that will be used as the user interface we interact with.

Finally we invoke the initialize() method.

And that’s it.
Here’s the complete source:

Example 2: Kotlin Android – ListView – Sort Ascending and Descending

Kotlin Android Simple ListView Sort Ascending and Descending Example

How to sort a simple listview in ascending and descending manner in Kotlin Android.

Let’s see how to sort data in a ListView in both ascending and descendig manner.

You click a button to sort in ascending, then click it again to toggle the sort into descending manner and vice versa.

Concepts You will Learn

Here are some of the concepts you will learn from this tutorial.

  1. What is a ListView?
  2. What is Data Sorting?
  3. How to sort a ListView Alphabetically in both ascending and descending manner.
  4. How to populate a ListView with an Array in Kotlin.

Video Tutorial

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel, ProgrammingWizards TV. Basically we have a TV for programming where do daily tutorials especially android.

What is Kotlin?

Kotlin is a programming language targeting the Java
platform. Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code.

Kotlin is usble almost everywhere Java is used today – for server-side development, Android apps, and much more.

Kotlin like Java is a statically typed programming language. This implies the type of every expression in a program is known at compile time, and the compiler can validate
that the methods and fields you’re trying to access exist on the objects you’re using.

(a). Defining Packages in Kotlin

Normally classes are organized in packages in Java. This applies to Kotlin as well.

Package specification should be at the top of the source file:

However, be aware that it’s not required to match directories and packages: source files can be placed arbitrarily in the file system.

(b). Defining Functions in Kotlin

Roughly speaking, functions in Kotlin are the equivalent of methods in java.

Functions can take input parameters and can return values. Here’s such a function:

This can be condensed into a single line given that it has an expression body and we can infer the retur types:

However, if functions do not return any meaningful value:

Читайте также:  Как включить андроид с разбитым экраном

Let’s see the full example.

ListView Sort Descending Unsorted ListView ListView Sort Ascending

1. Resources.

Android platform provides a powerful and flexible way of adding static content as a resource.

These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.

Resources belong to a given type. These types can be:

  1. Drawable.
  2. Layout.
  3. Value.

Let’s start by looking at the layout resources

(a). activity_main.xml

This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

In this case we use the following widgets:

  1. RelativeLayout – our viewgroup.
  2. TextView – to render our data.
  3. Button – To toggle sort order.
  4. ListView – To render both our sorted and unsorted data.

2. Kotlin Code

Kotlin is our programming language in this case.

(a) MainActivity.kt

3. Download

You can download full source code below.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Our YouTube Channel
2. YouTube Watch Video Tutorial
4. Camposha View All ListView Tutorials

Example 3: 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.

4. MainActivity.java

Here’s our main activity.

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.

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.

Download

Resource Link
GitHub Browse Browse
GitHub Download Link Download

Example 4: Kotlin GridView Sort Ascending and Descending

(a). build.gradle(app level)

Inside our app level build.gradle first you want to make sure that Kotlin plugin has been added as a dependency.

Also that it has been applied. Check below.

Normally if your are using android studio, just mark include kotlin in the Create Project and these will be done for you by the IDE.

(b). activity_main.xml

This layout will get inflated to our Main Activity layout.

It’s an XML file. XML normally stands for eXtensible Markup Language and is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

Android user interfaces are normally written in XML format. This makes them agnostic to the logic code written in Kotlin.

The encoding formats used with XML documents are either utf-8 or utf-16 , normally and in this case we use the former.

We have a RelativeLayout element as the root element. This layout normally arranges its children relative to other each other.

The first of those children is the extView, a View that is meant to render static Text. In this case we use it show the header label of our Kotlin Android application.

Then we will have another sibling element called GridView. This is a widget which is an adapterview. It’s similar to other adapterviews like ListView and Spinner in that they render lists of data and need an adapter to bind that data.

However GridViews normally render data in a two-dimensional format, that is rows and columns.

Lastly we have a button that is meant to toggle sort between ascending and descending.

Let’s now move to our MainActivity class.

(c). MainActivity.kt

1. What is an Activity in Kotlin Android?

Generally an activity is a single, focused thing that the user can do. Users normally act when they are interacting with your application.

This act may be sending an email or playing some music, or clicking a button. In Kotlin Android, or Android as a whole, they act on Activities.

An Activity is an android component so is fundamental to how android works. Activities have life cycle methods representing various stages in its life cycle.

Activities get created by deriving from android.app.Activity as we do here in Kotlin:

Of course we’ve already imported some packages:

2. Create Instance Properties

These include properties of type GridView and Button, which are our user interface widgets.

The GridView will be used to contain the data that need to sorted.

These two are not null and yet we don’t want to initialize them in the constructor, the way any non-null property has to. So we mark them as lateinit .

Then we create a property to act as our data source. We use the arrayOf() function to create an array of galaxies data:

Then we turn that Array into a List using the asList() method of the java.util.Arrays class:

And finally two helper properties to help us maintain state of sorting, whether data is unsorted or sorted in ascending or sorted in descending manner.

3. Sort Data in Ascending or Descending Manner via Collections

Then we come to how we will actually sort our data.

Fortunately we have the Collections class which will allow us do that easily.

But what is this Collections class?

Please don’t confuse it with Collection which is the root interface of the Collection hierarchy.

Collections on the other hand is a class that consists exclusively of static methods that operate on or return collections.

It derives from the Object class:

Among those static methods we are interested in the sort() and reverse() .

sort() will sort data in ascending manner. Then reverse() can reverse the already sorted data in descending manner.

You can see we reverse the state after sorting.Note that we have one button that will sort our data in descending manner the first time it’s clicked.

Then when clicked again it simply reverses it and then updates or negates the state of sortAscending variable.

So we will subsequently be toggling between the ascending and descending sort orders.

4. Bind Data to GridView Kotlin Android

Yeah we bind data to GridView using ArrayAdapter:

We listen to onClick events and show a Toast message with the clicked ite,.

Well here’s the full Kotlin source code.

Full Code

Our Kotlin MainActivity class.

(d). Results

I used Nox Player Emulator.

First unsorted data in our gridview. This before the user clicks the Toggle Sort button:

Kotlin Android Sort GridView

Then sorted data in ascending manner. This after he’s clicked the Toggle Sort button:

Kotlin Android Sort GridView

And lastly data sorted in descending manner. The data was first sorted in ascending manner. He clicks Toggle Sort and we toggle the sort to descending order:

Kotlin Android Sort GridView

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Читайте также:  About huawei android phones
Оцените статью