I have various location names and their latitude and longitude coming from server side. I am putting them in a list view using custom adapter. In the adapter, I have written the code to calculate the distance of the location from my current location. Every thing is working fine, But I want to sort my list by distance. I am unable to figure out how to do it.
My Activity code is:
List<String> Names = new ArrayList<String>();
List<String> MinLevel = new ArrayList<String>();
Names=db.getId();
MinLevel=db.getMinLevel();
MapAdapter ad=new MapAdapter(this, Names,MinLevel);
lv.setAdapter(ad);
The MapAdapter
private final Context context;
private List<String>Name=new ArrayList<String>();
private List<String>Min=new ArrayList<String>();
PharmacyDB db;
public MapAdapter(Context context,List<String>phname,List<String>phmin) {
super();
this.context = context;
this.Name=phname;
this.Min=phmin;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.test_adapter,parent, false);
db=new PharmacyDB(context);
final TextView pharname = (TextView)v.findViewById(R.id.test_ad_name);
final TextView distance = (TextView)v.findViewById(R.id.test_ad_dist);
final TextView rad_min = (TextView)v.findViewById(R.id.test_rad);
final RelativeLayout det=(RelativeLayout)v.findViewById(R.id.details);
pharname.setText(db.getPharmacyName(Name.get(position)));
if(!Min.get(position).equals("null")&&!Min.get(position).equals(null)){
rad_min.setText(Min.get(position));
}
else{
rad_min.setText("NA");
}
if(!db.getLat(Name.get(position)).equals("") && !db.getLat(Name.get(position)).contains("null") && !db.getLat(Name.get(position)).equals(null)&&!db.getLat(Name.get(position)).startsWith("0")){
float dis= distFrom((float)MapTest.mLatitude, (float)MapTest.mLongitude, Float.parseFloat(db.getLat(Name.get(position))), Float.parseFloat(db.getLong(Name.get(position))));
int d=Math.round(dis);
if(d<1000){
distance.setText(String.valueOf(d)+ " Meters");
}
else{
if((d/1000)<50)
distance.setText(String.valueOf(d/1000)+ " Kms");
else
distance.setText("NA");
}
}
else{
distance.setText("NA");
}
return v;
}
@Override
public int getCount(){
// TODO Auto-generated method stub
return Name.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}