Search code examples
androiddatabaselistviewsortingcursor

Sorting a listview on calculated data retrieved from database


I have a list of adverts that is being populated by a custom cursoradapter. I would like for the list to be sorted depending on the distance of the shops location from the user.

I'm having a little trouble implementing this. At the moment, I have the shops location stored in the database as latitude and longitude, I take it out and do some calculations to work out the distance. I currently just output the distance of each shop in each row in the listview, however I would like the listview sorted on the distance, with the nearer adverts shown first. I can't really think how to do this.

I have thought about re-querying the database, however I'm not sure if I could compare my calculated distances to the lat/long fields stored about a certain shop.


Solution

  • first we need to calculate the distance using Haversine formula from the current user position and the destination coordinate, then we need to store the calculated distance in the database . finally we can query the database with distance in ascending order.