Android sort ListView

In this Android tip, I am going to show you how to sort a ListView in ascending or descending order. The ActionProvider is customized to display actions menu on the action bar to allow the user to select its action items to sort the ListView.
To display a ListView object in the Activity, I use ListFragment as discussed in the previous tutorial (ListFragment Example). However, you need to modify the LstFragment class to pass an ArrayList object to the ArrayAdapter's constructor when you create an object of the ArrayAdapter. You also need to add two methods, sortAsc() and sortDesc(), and the Sorter class. The sortAsc() is called to sort the ArrayList object in ascending order and the sortDesc() sorts the ArrayList object in descending order. These methods are called when the user selects action menu items provided by ActionProvider from the action bar. The Sort class implements the Comparator interface so that you can sort the ArrayList object in ascending or descending order.





import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LstFragment extends ListFragment{
static ArrayList<String> data_source;
static ArrayAdapter<String> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragmentlayout, container, false);
     // Create an array of string to be data source of the ListFragment
     String[] datasource={"Juice","Pear","Lettuce","Cheese","Orange","Sandwich","Chicken"};
     data_source=new ArrayList<String>(Arrays.asList(datasource));
     // Create ArrayAdapter object to wrap the data source
     adapter=new ArrayAdapter<String>(getActivity(),R.layout.rowlayout,R.id.txtview,data_source);
     // Bind adapter to the ListFragment
     setListAdapter(adapter);
     // Retain the ListFragment instance across Activity re-creation
     setRetainInstance(true);
     return rootView;
    
   }
public static void sortList(int order){
   Collections.sort(data_source, new Sorter(order));
   adapter.notifyDataSetChanged();

}
// handle Item click event
public void onListItemClick(ListView l, View view, int position, long id){
   ViewGroup viewg=(ViewGroup)view;
  TextView tv=(TextView)viewg.findViewById(R.id.txtview);
  Toast.makeText(getActivity(), tv.getText().toString(),Toast.LENGTH_LONG).show();
}

static class Sorter implements Comparator<Object>{
  int order=-1;
  Sorter(int order){
     this.order=order;
}

public int compare(Object ob1,Object ob2){
  if(ob1.toString().compareTo(ob2.toString())==0) return 0;
  else if(ob1.toString().compareTo(ob2.toString())<0)
   return order;
  else
   return(-1*order);
     }

   }

}

For other tasks that are required to display the ListView object in the Activity, you need to follow the ListFragment Example Tutorial.
Now to use the ActionProvider to display action menu on the action bar, first you need to create a menu layout file called menu.xml file. You use the actionProviderClass attribute to specify the class that extends the ActionProvider. The class is called MySortActionProvider which its content is shown below.

MySortActionProvider.java

import android.content.Context;
import android.support.v4.view.ActionProvider;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.SubMenu;
import android.view.View;

public class MySortActionProvider extends ActionProvider implements OnMenuItemClickListener {
   private Context mContext;

   public MySortActionProvider(Context context) {
      super(context);
      mContext = context;
  }
@Override
   public View onCreateActionView(){
      return null;
   }
@Override
  public boolean hasSubMenu(){
    return true;
    }
@Override
  public void onPrepareSubMenu(SubMenu subMenu){
    subMenu.clear();
    subMenu.add("Sort in ascending").setOnMenuItemClickListener(this);
    MenuItem item1=subMenu.getItem(0);
    item1.setIcon(android.R.drawable.arrow_up_float);
    subMenu.add("Sort in descedning").setOnMenuItemClickListener(this);
    MenuItem item2=subMenu.getItem(1);
    item2.setIcon(android.R.drawable.arrow_down_float);

}
@Override
   public boolean onMenuItemClick(MenuItem item){
     if(item.getTitle().equals("Sort in ascending"))
       LstFragment.sortList(-1);
       else
      LstFragment.sortList(1);
    return true;
   }
}


Here is the menu xml file that has an menu item pointing the MyActionProvider class. You may change the icon_sort image your icon image. Your icon image file must be placed in the drawable directory.
menu.xml file

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
  
<item
   android:id="@+id/menu_sort"
  android:icon="@drawable/icon_sort"
  android:title="Sort"
  yourapp:actionProviderClass="com.example.andexamples.MySortActionProvider"
  yourapp:showAsAction="always"
/>
</menu>


In the onCreateOptionsMenu(), you need to inflate the menu.xml file instead of the main.xml file to display the action menu provided by the ActionProvider on the action bar.

public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.menu, menu);
   return true;
}


Android-sort-ListView

Posted by: Dara | post date: 10-22-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.