xtensivearts - One Leap Ahead
Quick Tip #2 – Sorting Lists

Quick Tip #2 – Sorting Lists

Posted 11/15/2009 - 8:02 pm by Mathias Reisch

The question came up if there is a simple way to sort lists and since the next video tutorial is dealing with Intents and not so much with lists, I thought I could just slip in this little quick tip that explains the basic method of sorting lists. There are actually two ways to achive a sorted list: you can sort the underlying data source or you can sort the elements in the actual list adapter. Lets see how that is done.

Sorting an Underlying Data Array

Back in episode #7 we used a simple string array to store names of people. Sorting an array is really easy. Suppose you have something like the following:

1
2
3
4
5
6
7
8
9
10
String[] names = {
	"Ashley","Brenda","Charles","Heather","Christine","Debbie","Jordan","Dan",
	"Erin","Eugene","Faith","Perry","Vincent","Frank","Gabrielle","Elliot",
	"Samuel","Harvey","Ian","Nina","Jessica","John","Kathleen","Keith","Laura",
	"Lloyd","Brad","Marion","Michael","Nathan","Olivia","Carla","Oscar","Paris",
	"Peter","Rachel","Richard","Aaron","Sandra","Taylor","Tyler","Veronica",
	"Isabella","Zoe","William","Christopher","Zachary","Trey","Jacob","Michael",
	"Ethan","Emma","Jayden","Emily","Sophia","Noah","James","Jonathan","Angel",
	"Samantha","Jack","Bob","Chase","Kayla"
};

This is actually the same array that was used in episode #7. Now if you want to sort this array, simply add the following line before you create the ArrayAdapter:

1
Arrays.sort(names);

If you create that ArrayAdapter with a sorted data source, the resulting adapter will also be sorted. Here is the complete code for creating a sorted list using the ArrayAdapter (from within a class that extends ListAcitvity just like in episode #7).

1
2
3
4
5
6
7
8
9
10
ArrayAdapter<String> adapter;
 
Arrays.sort(names);
 
adapter = new ArrayAdapter<String>(
		this,
		android.R.layout.simple_list_item_1,
		names);
 
setListAdapter(adapter);

Easy, huh? Arrays is kind of a helper class that provides a couple of array-related methods. Be sure to import the class using:

1
import java.util.Arrays;

Sorting an ArrayAdapter

Another way to sort a list made from an ArrayAdapter, is by sorting the adapter itself. This is helpful if you want to sort or reorder the elements of a list during runtime, for example when you add elements to the list. Again, this is quite easy but you have to wrap your head around a new concept: Comparators. A Comparator is an abstract class that lets you implement a method called compare(). The whole purpose of this method is to compare two objects. For the sake of simplicity lets call these objects A and B. Now, the magic lies in the return value of that compare() method. It should return an integer < 0 if A is less than B, 0 if A is equal to B and an integer > 0 if A is greater than B. But how is that helpful? The ArrayAdapter comes with a sort method that takes a Comparator as an argument. By implementing a very simple compare() method we can run through the whole list and sort all elements. Sounds a bit confusing? Well, if you see it written out, it is actually very easy. Take a look at this:

1
2
3
4
5
adapter.sort(new Comparator<String>() {
	public int compare(String object1, String object2) {
		return object1.compareTo(object2);
	};
});

First we call the sort method of our ArrayAdapter and pass a new instance of a Comparator class to it. Note that we datatype it to a String (between the angled brackets) since we want to compare string objects (our names). In this new inner class we have to implement the abstract compare() method. The method takes two String parameters (or really any other data type depending on what you datatyped the class to). Inside that method we compare object1 to object2 and return the result. The compareTo() method of the string class returns actually the same values that we need for our method, meaning something < 0 if object1 is less than object2, 0 if both are equal and a value > 0 if object1 is greater than object2. And that is all there is to it. However, make sure you put the above code somewhere after you created and assigned your data array to the ArrayAdapter. Here is the complete code block again:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ArrayAdapter<String> adapter;
 
adapter = new ArrayAdapter<String>(
		this,
		android.R.layout.simple_list_item_1,
		names);
 
adapter.sort(new Comparator<String>() {
	public int compare(String object1, String object2) {
		return object1.compareTo(object2);
	};
});
 
 
setListAdapter(adapter);

If you want to sort the list backwards, you can switch object1 and object2 in the compareTo() method like this:

1
2
3
4
5
adapter.sort(new Comparator<String>() {
	public int compare(String object1, String object2) {
		return object2.compareTo(object1);
	};
});

Also, if you sort the list during runtime, it is always a good idea to notify the application that the data set has changed. So after sorting the list, you might want to put this line:

1
adapter.notifyDataSetChanged();

Sorting Other Adapters

Sorting Lists that have other data sources like databases or XML documents is a bit different and way beyond the scope of this quick tip. However, in one of the next video tutorials we will cover database access and once we have uncovered the mysteries of database queries and Cursors and all that stuff, you will see that sorting those list is not that hard either.

Anyway, I hope some of you will find this quick tip useful. If you have any questions about this, feel free to ask. I will do my very best to answer them. Until next time, happy coding.

Related posts:
  1. Episode #9 – Lists: Item Clicks
  2. Quick Tip #1 – Create an Eclipse Project from an Archive File
  3. Episode #7 – Using Basic Lists

Why Not Leave a Comment?

Name:*
E-Mail:*
Website:
Comment:*

Comments

PJFonseca

11/16/2009 – 9:08 am

Hummm, i don’t know if it was my curiosity that made you write this article, but if it was, thanks alot for the quick answer.

Now i know how to sort an array :), ready to go listen to the next article (#9) and apply #8 to my little test app.

Mathias Reisch

11/16/2009 – 10:00 am

@PJFonseca
Good to hear that this article was useful for you. You were actually one of a few people who wanted to know about sorting lists. So instead of answering that question individually via email, I thought it would make a nice quick tip for everyone and so here it is. :-)

KC

03/06/2010 – 4:11 am

Very good tips! And I want to continue trying it out based on your Episode #9. Appreciate if you can throw some light on how to add item to your ArrayList during runtime? Thx for your excellent videos.

Stephen

07/26/2010 – 3:20 am

Yeah, i would also like to see how to add items to the array list during the running program.