0

so this is how my firebase look like:

my firebase

I want to get to all children of 9-12-2021. I succeeded to access this node and print the value inside it, but now I'm trying to save all his children's' value in a set but the function first return and then do the inner class of OnDataChange

  FirebaseDatabase.getInstance().getReference().child("Appointment").child(date)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        String user = snapshot.getKey();
                        mySet.add(Integer.parseInt(user));
                    }

                }

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

                }
            });
    return times;

how can I use this listener to save all date in the set before he returning from the function? (actually i want to add another function call before the last line )

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Hay Asa
  • 9
  • 3
  • You need to implement a callback using an interface – Adarsh Yashvanth Dec 09 '21 at 14:24
  • can you explain what do you mean "implement a callback using an interface"? – Hay Asa Dec 09 '21 at 14:51
  • Data is loaded from Firebase asynchronously, because it has to come from the cloud. While the data is being loaded, your main code continues and then when the data is available your `onDataChange` is called with it. This means that in your code the `return times` runs before the `mySet.add(Integer.parseInt(user))` has ever run, and thus returns an older result than you expect. The solution for this is always the same: any code that needs the data from the database, needs to be inside `onDataChange`, be called from there, or otherwise synchronized. I linked some questions where this is covered. – Frank van Puffelen Dec 09 '21 at 15:00

0 Answers0