Android按距离重新订购适配器

时间:2017-09-06 11:02:20

标签: java android sorting adapter

我正在尝试按距离重新排序我的项目列表(使用android getListView,而不是自定义),我遇到了问题。

我使用适配器(SomeAdapter)中的Maps Utils 来获得以米为单位的球形距离(双倍)。

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);
        }
    }

谢谢

2 个答案:

答案 0 :(得分:7)

只需在Comparable班级

中实施Raids界面即可
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();

答案 1 :(得分:1)

鉴于你的代码:

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;
    }

}