简体   繁体   English

如何按自定义顺序放置ListView?

[英]How do I put my ListView in a custom order?

I am creating a ListView with data load from my server! 我正在创建从服务器加载数据的ListView! How can I order my List depending on the value of variable(eg double)? 如何根据变量的值(例如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! DISTANCE是我要作为订单标准的变量。谢谢!

First of all why don't you create a class to represent your Driver data instead of using HashMap ? 首先,为什么不创建一个类来表示驱动程序数据而不是使用HashMap?

Anyway what you're looking for can be done by using Collections.sort , what you will have to do is : 无论如何,您都可以使用Collections.sort完成,您需要做的是:

  • Create a class that implements Comparator interface 创建一个实现Comparator接口的类

     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 这是一个关于比较器的好教程: Java中的集合

You should subclass the ListView adapter. 您应该子类化ListView适配器。 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. 然后将您的项目添加到适配器,对其进行排序,最后将适配器设置为ListView。

Listview or not it is not really important here. 是否使用Listview并不是很重要。 What you should do is simply sort your data prior handing it to your listview. 您应该做的就是简单地对数据进行排序, 然后再将其交给列表视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM