Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android re-order adapter by distance

I'm trying to re-order my items list (Using android getListView, not custom) by distance and I'm having issues.

I'm getting the Spherical distance in meters (double) using Maps Utils inside the adapter ( SomeAdapter ).

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

But after I fill the adapter (AsyncTask) I need to short by distance on my onPostExecute and I have no idea.

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

Thank you

like image 798
FilipeOS Avatar asked Sep 06 '17 11:09

FilipeOS


2 Answers

Just implement the Comparable interface in your Raids class -

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

Then call Collections.sort on it -

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

And update the adapter -

listViewAdapter.notifyDataSetChanged();
like image 133
jL4 Avatar answered Nov 16 '22 02:11

jL4


Given your code:

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

You need:

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

}

and

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

}
like image 1
Nick Cardoso Avatar answered Nov 16 '22 00:11

Nick Cardoso