Android按距离重新sorting适配器

我试图重新sorting我的项目列表(使用android getListView,而不是自定义)的距离,我有问题。

我使用适配器内部的地图实用程序(SomeAdapter)获取以米为单位的球面距离(双倍)。

double distance = SphericalUtil.computeDistanceBetween(fromCoord, toCoord);

但是,我填充适配器(AsyncTask)后,我需要在我的onPostExecute短距离,我不知道。

  @Override protected void onPostExecute(Boolean result) { try { SQLiteHelper dbHelper = new SQLiteHelper(getActivity()); pds = new SomeDataSource(dbHelper.db); ArrayList<Raids> some = pds.getAllRaids(); SomeAdapter listViewAdapter = new SomeAdapter(getActivity(), some); getListView().setAdapter(listViewAdapter); SharedPreferences somename = context.getSharedPreferences("SomeName", Context.MODE_PRIVATE); Boolean UserOrder = somename.getBoolean("UserOrder", false); if (UserOrder){ } } catch (SQLiteException | NullPointerException s) { Log.d("SomeName", "SomeFrag:", s); } } 

谢谢

Solutions Collecting From Web of "Android按距离重新sorting适配器"

只需在你的Raids类中实现Comparable接口 –

 class Raids implements Comparable<Raids> { private double distance; ... @Override public int compareTo(Raids instance2) { if (this.distance < instance2.distance) return -1; else if (this.distance > instance2.distance) return 1; else return 0; } } 

然后调用Collections.sort就可以了 –

 ArrayList<Raids> some = pds.getAllRaids(); Collections.sort(some); 

并更新适配器 –

 listViewAdapter.notifyDataSetChanged(); 

给你的代码:

 ArrayList<Raids> some = pds.getAllRaids(); SomeAdapter listViewAdapter = new SomeAdapter(getActivity(), some); 

你需要:

 class SomeAdapter ... { private ArrayList<Raids> mData; //TODO: now call this method instead of computeDistanceBetween directly private void calculateForitem(Raids item) { double distance = SphericalUtil.computeDistanceBetween(item.fromCoord, item.toCoord); item.setDistance(distance); Collections.sort(mData); //the list inside adapter notifyDataSetChanged(); } } 

 class Raids implements Comparable<Raids> { private double distance; ... @Override public int compareTo(Raids instance2) { return (this.distance < instance2.distance)? -1 : (this.distance > instance2.distance)? 1 : 0; } }