CursorAdapter dynamic sorting
Asked Answered
S

1

7

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?

Spongin answered 7/11, 2013 at 14:20 Comment(0)
R
4

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.

Rosannrosanna answered 3/3, 2015 at 14:4 Comment(1)
Totally useful when trying to sort a cursor loader result based on distanceSchaab

© 2022 - 2024 — McMap. All rights reserved.