1

I want to make two database calls one inside the other and make use of the first call data. Since firebase database calls are asynchronous this is not behaving the way I want. I HAVE two database nodes Users, Chats.

enter image description here

enter image description here

I want first query through one Users at a time and take the user id and then query through the Chats model and check if the id in Users and Chats nodes are same

Something like this.

database.getReference().child("Users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {

        list.clear();
        for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
            users = dataSnapshot.getValue(Users.class);
            users.setUserId(dataSnapshot.getKey());
            database.getReference().child("Chats").child(auth.getUid() + users.getUserId()).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if(snapshot.exists()){

                        //ADD USER TO LIST UPDATE UI

                        list.add(users);
                    }
                    else{
                        //DON'T ADD USER
                    }
                }

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

                }
            });

Hope I made the problem clear.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Lahiri17
  • 21
  • 3
  • 1
    What you are trying to do, it's pretty common. What exactly in this code doesn't work the way you expect? – Alex Mamo Feb 02 '21 at 13:42
  • The Chats onDataChange Listener is running at last after all Users are fetched from database on the first listener , so as a result only last userid is provided to the Chats node – Lahiri17 Feb 02 '21 at 14:03
  • Firebase API is asynchronous. So please check this [answer](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774) to see how can you solve this using a custom callback. – Alex Mamo Feb 02 '21 at 14:05

0 Answers0