1

I'm cycling through some children in firebase to see if the value of a key exists, and in my addListenerForSingleValueEvent function the key is found and a global boolean is set to true. However, after the function, the variable is set as false so the program does not enter the second if statement.

referenceClasses.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            if (snapshot.getKey().compareTo(combinedString) == 0) {
                                found = true;
                                break;
                            }
                        }
                    }

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

                if(found) {
                   //...
                }

I know found is set to true within the addListenerForSingleValueEvent through various inputs to my database. the boolean is instantiated as

boolean found;

globally, before any other functions. I even tried to implement two functions, one which sets the boolean and another which returns it but I ended up with the same results of the boolean being true within addListenerForSingleValueEvent and false in the if statement. Any ideas?

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
Alisha
  • 105
  • 1
  • 11
  • The answer from AvidRP is indeed the reason: your `if(found)` now runs before the `onDataChange` has run, so `found` hasn't been set yet. You can't make the code work (or at least not without Android becoming unhappy with your app). But there are other ways around as shown in my answer here: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Dec 05 '18 at 08:04

1 Answers1

6

This is happening because the firebase calls are asynchronous and as a result your program might be hitting the if block before it even enters the onDataChange() method. To see if this is the case, you could put a breakpoint inside onDataChange and a breakpoint on the if(found) line and see which one gets executed first.

If all you are trying to do is execute some code once found is set to true, then you should just move the whole if block inside onDataChange.

Hopefully this helps!

AvidRP
  • 373
  • 2
  • 11