Sunday, November 23, 2014

Tutorial 12 : Sort List Example

Hi, guys! Sorry for long time, didn't update my blog because recently are busy with my personal stuff. In this tutorial, we will learn how to sort the list by ascending or descending order. This able to done by using sort() method and comparator class.

1. Sort Method

Ascending Order

By referring tutorial 9, we are creating a list view layout and put some elements in an array. Now we would like to modify the previous project in order to sort the them in ascending order. Use the Arrays.sort(items) command to sort them as shown in Figure 12.1.

public class ListMonth extends ListActivity {

    static final String[] MONTHS = new String[] { "January", "February",
             "March", "April", "May", "June", "July", "August",
             "September", "October", "November", "December" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Arrays.sort(MONTHS);

       setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_list
       _month, MONTHS));

        ListView listView = getListView();
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                   int position, long id) {
               // When clicked, show a toast with the TextView text
               Toast.makeText(getApplicationContext(),
               ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
             }
        });

    }
Figure 12.1


Therefore, the items in the list view will be arranged with alphabetical pattern (e.g. April, August, December, February, ......) as shown in Figure 12.2.

Figure 12.2

If you are using an ArrayList to store the items, then Collection.sort(ArrayList) command is used to sort the items as shown in Figure 12.3.

List MONTHS = new ArrayList(); 

@Override
protected void onCreate(Bundle savedInstanceState) {   
      super.onCreate(savedInstanceState); 


      MONTHS.add("January");
      MONTHS.add("February");
      MONTHS.add("March");
      MONTHS.add("April");
      MONTHS.add("December");

      Collections.sort(MONTHS);
Figure 12.3

Descending Order

By using sort method, we also able to arrange the items in descending order. It is very easy to apply. In Array.sort(<String>,<Comparator>) and Collections.sort(<List>,<Comparator>) method, actually there is a comparator option for us to choose the arrangement preference. It can be set as ascending order or descending order (by default is ascending order).

We can apply the code as Figure 12.4 in order to arrange the items in descending order as shown in Figure 12.5.

List MONTHS = new ArrayList(); 

@Override 
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      MONTHS.add("January");
      MONTHS.add("February");
      MONTHS.add("March");
      MONTHS.add("April");
      MONTHS.add("December");

      //Collections.sort(MONTHS);
      Collections.sort(MONTHS, Collections.reverseOrder());
Figure 12.4

Figure 12.5

2. Comparator Class

Sort() actually is a method which is provided by Java to let us to arrange items in different ways. That is user friendly for the new user, but it might be not robust enough if you want to create new way to arrange the items.

Now we would learn how to create a new comparator class to implement in the sort() method. 

At this part, we would like to arrange the time (AM and PM) which is combined which the number (e.g. 12.30AM, 1.03PM, 4.23PM, 12.50AM,....). They will be not in a proper arrangement if we are simply used the sort() method as shown in Figure 12.6.

Figure 12.6

Thus, we need to create our own class in order to make them arrange accordingly. Let's us try to make it REAL.

First, we create a new class to get() and set() the information from the list.  Go to the project file, right click on it, select New > java Class and named the class as Time.

In this class, we stored two information, timeNumber and period in string. Besides that, create get() function for each info to return value to the call function and set() function to store the value from main. The sample of code is shown as Figure 12.7.

package com.hmytechnology.manyeap.listmonth;

import java.util.Comparator;

/**
 * Created by manyeap on 11/22/14.
 */
public class Time implements Comparable<Time>{

    private String timeNumber;
    private String period;

    public Time(String timeNumber, String period) {
        super();
        this.timeNumber = timeNumber;
        this.period = period;
    }

    public String getTimeNumber() {
        return timeNumber;
    }

    public void setTimeNumber(String timeNumber) {
        this.timeNumber = timeNumber;
    }

    public String getPeriod() {
        return period;
    }

    public void setPeriod(String period) {
        this.period = period;
    }
Figure 12.7

We can change the properties of sort() function as well, for example rearrange them according the period of day (AM or PM). Implement comparable method in the Time class and add-on a compareTo() function in the class as shown in Figure 12.8.

public int compareTo(Time compareTime)
{
       String compareNumber = ((Time) compareTime).getPeriod();
       return this.period.compareTo(compareNumber);
}
Figure 12.8

Now, when we apply the sort() function, we will able get the output as shown in Figure 12.9.

Figure 12.9

In the next step, we need to rearrange the time number since they are not arrange in a right way yet. Therefore, create a checking condition to split the different period of day and store them in different array (e.g. timeAM and timePM).  Then, sort the items in timeAM and timePM. Following by that, restored the items into time array. The sample code is shown in Figure 12.10.

String[] timeAM = new String[2];
String[] timePM = new String[2];

for(int i=0;i<4;i++)
{
       if(time[i].getPeriod() == "AM")
       {
            timeAM[i] = time[i].getTimeNumber();
       }
       else
       {
            timePM[i-2] = time[i].getTimeNumber();
       }
}

Arrays.sort(timeAM);
Arrays.sort(timePM);

for(int i=0; i<4; i++)
{
       if(i<2)
       {
             time[i].setTimeNumber(timeAM[i]);
       }
       else
       {
             time[i].setTimeNumber(timePM[i-2]);
        }
}
Figure 12.10

In the end, the time will be arranged in ascending order accordingly and the output as shown in Figure 12.11.

Figure 12.11

Good job for us. We are SUCCESSFULLY done it completely. You can have a download the code at here, if you need it. In the next tutorial, we will learn how to resort the listview by using drag and drop sort function. Hope you all enjoy my tutorial. :D

1 comment: