I have a ListActivity populated by the following Array Object:
public class VideoLocation {
public String deleted_at = null;
public int documentary_video_length = -1;
public int id = -1;
public double latitude = 0d;
public double longitude = 0d;
public int position = -1;
public String updated_at = null;
public String name = null;
public String text = null;
public String documentary_video_url = null;
public String documentary_thumbnail_url = null;
public String audio_text_url = null;
public Footage[] footages = null;
public VideoLocation(){
}
I need to sort the ListActivity based on the distance between the Location and the User.
I don’t have any trouble in sorting the ‘name’ String alphabetically, I use this method:
public void sortAZ(){
Arrays.sort(videoLocations, new Comparator<VideoLocation>() {
@Override
public int compare(VideoLocation lhs, VideoLocation rhs) {
return lhs.name.compareTo(rhs.name);
}
});
}
but the method can’t be used for ‘double’ data type, which I need for ‘latitude’ and ‘longitude’. Besides there’s no attribute ‘distance’ for the object VideoLocation.
How am I able to sort it out even when I can calculate the distance between the Location and the User?
UPDATE
THIS IS THE FINAL SOLUTION! WORKS LIKE A CHARM
public void sortNearby(){
Arrays.sort(videoLocations, new Comparator<VideoLocation>() {
@Override
public int compare(VideoLocation lhs, VideoLocation rhs) {
double lat = location.getLatitude();
double lng = location.getLongitude();
double lat1 = lhs.latitude;
double lng1 = lhs.longitude;
double lat2 = rhs.latitude;
double lng2 = rhs.longitude;
double lhsDistance = countDistance(lat,lng,lat1,lng1);
double rhsDistance = countDistance(lat,lng,lat2,lng2);
if (lhsDistance < rhsDistance)
return -1;
else if (lhsDistance > rhsDistance)
return 1;
else return 0;
}
});
}
public double countDistance(double lat1,double lng1, double lat2, double lng2)
{
Location locationUser = new Location("point A");
Location locationPlace = new Location("point B");
locationUser.setLatitude(lat1);
locationUser.setLongitude(lng1);
locationPlace.setLatitude(lat2);
locationPlace.setLongitude(lng2);
double distance = locationUser.distanceTo(locationPlace);
return distance;
}
Either give
VideoLocationa field to hold the distance from the user, calculate that for each of your locations, and then sort with aComparatorthat compares the distances, or make aComparatorthat computes both distances and compares them.The first approach requires an extra field in the
VideoLocationwhich you may not want to have. The second approach does some redundant computation (computing distances something like 2n log n times instead of n times). Take your pick; either will work fine and neither is all that expensive.