0
public void getListHotel(String uid){
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        List<Hotel> list = new ArrayList<>();
        List<String> listIDHotel = new ArrayList<>();


        db.collection("users/" + uid + "/favorites").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                if (error == null){
                    if (!value.isEmpty()){
                        for (QueryDocumentSnapshot doc : value) {
                            Log.d("favorite1", doc.getId());
                            listIDHotel.add(doc.getId());
                        }
                    }else{

                    }
                    Log.d("FAVVM1", String.valueOf(listIDHotel.size()));
                }
            }
        });

        if(listIDHotel.size() == 0){
            Log.d("FAVVM", "empty");
            return;
        }
}

I have a function but when I run app, I watch Log "FAVMM1": 1 but Log "FAVMM": 0. I don't understand why size of list become 0

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Data is loaded from Firestore (and most modern cloud APIs) asynchronously, since it may have to come from a server. While the data is being loaded you main code continues to execute, so that the user can continue to use the app. Then once the data is available, your `onEvent` gets called with that data. What this means is that your `if(listIDHotel.size() == 0){` runs before the ` listIDHotel.add(doc.getId());` has ever executed. If you check the order of the log output, you can easily confirm that. The solution is always the same: any code tht needs the data, has to be inside `onEvent`. – Frank van Puffelen Apr 26 '22 at 03:23
  • I linked some questions that show how to deal with this problem, but you can fine many more here: https://stackoverflow.com/search?q=%5Bgoogle-cloud-firestore%5D%5Bandroid%5D+asynchronous – Frank van Puffelen Apr 26 '22 at 03:23
  • @FrankvanPuffelen You are true. But I want to get list id hotel before, then I use that list to get detail of item. How can I do that ? –  Apr 26 '22 at 03:41
  • The questions I linked show all options. – Frank van Puffelen Apr 26 '22 at 04:12

0 Answers0