0

How can sort the distance from near to far?

I will calculate how far the user is from each point.

this is my code

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Campsite");
        Query query = reference.orderByChild("country").equalTo(country);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                progressDialog.dismiss();
                if(seatch_bar.getText().toString().equals("")){
                    camperSiteModel.clear();
                    for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                        CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);

                        double radLat1 = rad(camperSiteModel1.getCamperSiteLatitude());
                        double radLat2 = rad(latitude);
                        double a = radLat1 - radLat2;
                        double b = rad(camperSiteModel1.getCamperSiteLongitude()) - rad(longitude);
                        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                                + Math.cos(radLat1) * Math.cos(radLat2)
                                * Math.pow(Math.sin(b / 2), 2)));
                        s = s * EARTH_RADIUS;
                        s = Math.round(s * 10000) / 10000;
                        Log.i("Distance",Math.ceil(s)+"");

                        camperSiteModel1.setDistance(Math.ceil(s));

                        camperSiteModel.add(camperSiteModel1);
                    }
                    camperSiteAdapter.notifyDataSetChanged();
                }
            }

I can know the distance from the user to each point, but now I want to display the way from near to far when I use the recyclerView

SAWYU
  • 119
  • 8
  • Try using `Collections.sort();` – Vishnu Sep 29 '21 at 14:11
  • @Vishnu May I ask, is it use in where ? – SAWYU Sep 29 '21 at 14:20
  • [1](https://stackoverflow.com/questions/23039744/how-to-sort-an-arraylist-of-objects) [2](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) [3](https://stackoverflow.com/questions/2535124/how-to-sort-an-arraylist-of-objects-by-a-property) <- These questions will help you with the implementation of `sort();` – Vishnu Sep 29 '21 at 14:59
  • like this ?? camperSiteModel1.setDistance(Math.ceil(s)); camperSiteModel.add(camperSiteModel1); Collections.sort(camperSiteModel, Collections.reverseOrder()); – SAWYU Sep 30 '21 at 12:37
  • `Collections.sort(camperSiteModel);` before passing the list to the adapter. You might have to implement a custom Comparator – Vishnu Sep 30 '21 at 17:33

0 Answers0