How to sort data in listview in Android Studio

Hamza Dev :

Can you help me please to sort data in listView the listView is linked with Firebase DataBase, I want to sort them by time, meaning that the last data that is added to Firebase appears first in the listview. please excuse me, I'm still beginner in Android Studio

I'm using this code to get the data from Firebase Database

ListView listLocation;
DatabaseReference databaseLocation;
List<Location> locationList;






    @Override
public void onStart() {
    super.onStart();

    databaseLocation.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            locationList.clear();
            for (DataSnapshot locationSnapshot : dataSnapshot.getChildren() ){

                Location location = locationSnapshot.getValue(Location.class);

                locationList.add(location);


            }
            LocationList adapter = new LocationList(getActivity(), locationList);


            Collections.reverse((List<LocationList>) adapter);

            listLocation.setAdapter(adapter);








        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
Oscar Emilio Perez Martinez :

It becomes a little difficult when you're not explaining how would you like to sort your collection. But i this case i'm assuming you're trying to sort by the distance.

So the code snippets would be as below.

  Collections.sort(adapter, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            Location l1 = (Location) o1;
            Location l2 = (Location) o2;
            return l1.getDistance().compareTo(l2.getDistance());
        }
    });

We're making a Comparator that can compare your objects, or if they are all instances of the same class, you can make that class implement Comparable. You can then use Collections.sort() to do the actual sorting.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=300200&siteId=1