Question

I currently use a CursorAdapter with a Loader. The data loaded by the Loader contains a location. I want to order my items from the nearest to the farthest. I already compute the distance to display it, I now need to find a way to dynamicaly sort the data.

I could probably modify the CursorLoader sort everytime my data change, but doing the same SQL query again and again just to change the order looks somehow overkill to me…

Is there any way to dynamically sort data in a CursorAdapter?

Was it helpful?

Solution

You should use sortOrder - last parameter of CursorLoader's contructor.

Let's assume your table has column named lat for latitude and lon for longitude. User's location also described via latitude/longitude userLat and userLon. For sorting we aren't need to know precise distance - approximate distance will be enough. For that You can use Pythagorean theorem.

sortOder will be like this: abs(lat - userLat)* abs(lat - userLat) + abs(lon-userLon)*abs(lon-userLon). This computation contains only supported by Sqlite operators.

Note 1: you have to change code above in order to provide correct String where userLat and userLon are replaced with their values.

Note 2: you can't use this formula to compute precise distance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top