Dimitris
Dimitris

Reputation: 247

How do I put my ListView in a custom order?

I am creating a ListView with data load from my server! How can I order my List depending on the value of variable(e.g. double)? To help you more, the app calculates the distance between devices and I want the list to stars from the min to max distance!Here is my code.Any Ideas?

public class DriversList extends ListActivity{

private ProgressDialog pDialog;

JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> driversList;

private static String url_all_drivers = "http://192.168.2.4/drivers/get_all_drivers.php";//192.168.2.4 , 10.0.2.2 , taxidroid.yzi.me

private static final String TAG_SUCCESS = "success";
private static final String TAG_DRIVERSID = "drivers";

private static final String TAG_ID = "id";
private static final String TAG_EMAIL="email";
private static final String TAG_NAME = "name";
private static final String TAG_SURNAME="surname";
private static final String TAG_TELEPHONE="telephone";
private static final String TAG_PLATE="plate";
private static final String TAG_CARMODEL="carmodel";
private static final String TAG_LATITUDE="latitude";
private static final String TAG_LONTITUDE="lontitude";
private static final String TAG_AVAILABLE="available";
private static final String DISTANCE="distance";
private static final String MILL="hh";
private double Clat,Clon;

 JSONArray drivers = null;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.drivers_list_layout);


 driversList=new ArrayList<HashMap<String,String>>();
 new LoadAllDrivers().execute();

Clat=getIntent().getExtras().getDouble("ClLat");
Clon=getIntent().getExtras().getDouble("ClLon");    
Toast.makeText(getBaseContext(), ""+Clat+""+Clon, Toast.LENGTH_LONG).show();
 }
class LoadAllDrivers extends AsyncTask<String, String, String>{

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(DriversList.this);
    pDialog.setMessage("Loading products. Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();}


@Override
protected String doInBackground(String... args) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();

      JSONObject json = jParser.makeHttpRequest(url_all_drivers, "GET", params);
      Log.d("All Drivers: ", json.toString());

     try {
           int success = json.getInt(TAG_SUCCESS);
               if (success == 1) {

                   drivers = json.getJSONArray(TAG_DRIVERSID);


             for (int i = 0; i < drivers.length(); i++) {
                 JSONObject c = drivers.getJSONObject(i);


                 String id = c.getString(TAG_ID);
                 String email=c.getString(TAG_EMAIL);
                 String name = c.getString(TAG_NAME);
                 String surname=c.getString(TAG_SURNAME);
                 String telephone=c.getString(TAG_TELEPHONE);
                 String plate=c.getString(TAG_PLATE);
                 String carmodel=c.getString(TAG_CARMODEL);
                 double lat=c.getDouble(TAG_LATITUDE);
                 double lon=c.getDouble(TAG_LONTITUDE);
                 String avail=c.getString(TAG_AVAILABLE);

                 double R = 6371; // earth’s radius (mean radius = 6,371km)
                 double dLat =  Math.toRadians(Clat-lat);

                 double dLon =  Math.toRadians(Clon-lon); 
                 double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                        Math.cos(Math.toRadians(Clat)) * Math.cos(Math.toRadians(lat)) * 
                        Math.sin(dLon/2) * Math.sin(dLon/2); 
                 double c1 = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
                 double d = R * c1;

                 double gg=d*1000;


                 HashMap<String, String> map = new HashMap<String, String>();


                 map.put(TAG_ID, id);
                 map.put(TAG_NAME, name);
                 map.put(TAG_SURNAME, surname);
                 map.put(TAG_CARMODEL, carmodel);

                 if (d<1) {map.put(DISTANCE,String.format("%.2f", gg)); map.put(MILL, "m"); }
                 else  {map.put(DISTANCE, String.format("%.2f", d)); map.put(MILL, "km"); }
                 driversList.add(map);



             }
         } else {runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(DriversList.this,"Αυτη τη στιγμη δεν υπαρχει διαθεσιμος οδηγος",Toast.LENGTH_SHORT).show();}});
         }
     } catch (JSONException e) {
         e.printStackTrace();
     }
    return null;
}

@Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {

    public void run() {
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                DriversList.this, driversList,
                R.layout.list_item, new String[] { TAG_ID,
                        TAG_NAME,TAG_SURNAME,TAG_CARMODEL,DISTANCE,MILL},
                new int[] { R.id.id, R.id.name,R.id.surname,R.id.carmodel,R.id.txtdistance1,R.id.txtmorkm});

        setListAdapter(adapter);


    }
});

}

   }

     }    

The DISTANCE is the variable that I want to be as the criterion for the order.Thanks in Advance!

Upvotes: 0

Views: 222

Answers (3)

Mr.Me
Mr.Me

Reputation: 9276

First of all why don't you create a class to represent your Driver data instead of using HashMap ?

Anyway what you're looking for can be done by using Collections.sort, what you will have to do is :

  • Create a class that implements Comparator interface

    public class DriverComparator implements Comparator<HashMap<String, String>> {
    
    public int compare(HashMap<String, String> o1,
            HashMap<String, String> o2) {
        double distance1 = -1;
        double distance2 = -1;
        try {
        distance1 = Double.parseDouble(o1.get("DISTANCE"));
        } catch (NumberFormatException ex){
    
        } catch (NullPointerException nex){
    
        }
        try {
            distance2 = Double.parseDouble(o1.get("DISTANCE"));
            } catch (NumberFormatException ex){
    
            } catch (NullPointerException nex){
    
            }
        if (distance1 == distance2){
            return 0;
        }
        if (distance1 > distance2) {
            return 1;
        }
        return -1;
    }
    

    }

  • Sort your list before pasing it to the adapter :

     Collections.sort(list, new DriverComparator());
    

Here is a good tutorial about Comparators: Collections in Java

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Listview or not it is not really important here. What you should do is simply sort your data prior handing it to your listview.

Upvotes: 0

SceLus
SceLus

Reputation: 1107

You should subclass the ListView adapter. There create a sort function. Any sort algorithm should do. Then add your items to the adapter, sort them and finally set the adapter to the ListView.

Upvotes: 0

Related Questions