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
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();
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With