1

I have a method that returns true if a child is present in the database and false if not. It looks like this:

boolean subscriber;
public boolean checkChatRoomMembership(String chatRoomUid) {
    mChatRoomMembers.child(chatRoomUid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(mAuth.getUid())) {
                subscriber = true;
            } else {
                subscriber = false;
            }
        }

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

        }
    });
    return subscriber;
}

Even though the the node is present in the database it returns false the first time the method is ran. The following times it returns true as it should. It is always the first time the activity is started that it returns false. Any ideas why?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
John
  • 447
  • 1
  • 8
  • 22
  • 1
    you're probably returning it before the operation completed, because it's async – a_local_nobody Jul 28 '19 at 18:39
  • You can't return something *now* that hasn't completed loading yet. So you'll either need to move the code that needs the data into `onDataChange`, or implement a custom callback. See https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener/33204705?r=SearchResults&s=2|0.0000#33204705, https://stackoverflow.com/questions/38456650/cant-get-values-out-of-ondatachange-method/38460676#38460676 and https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Jul 28 '19 at 18:48

1 Answers1

3

When the function is called the first time, callbacks inside the function has not been called. Yet data is not retrieved and your function return default value of "subscriber" variable. After the first call to this function "subscriber" value updates when the callback is called.

public void checkChatRoomMembership(String chatRoomUid) {
mChatRoomMembers.child(chatRoomUid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.hasChild(mAuth.getUid())) {
            // true, do you work here
        } else {
            // false, do you work here
        }
    }

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

    }
});

}

Hope this will help you.

Wajahat Hussain
  • 234
  • 2
  • 7
  • Okay thanks. Do you know how I can solve this? – John Jul 28 '19 at 18:45
  • My suggestion is don't make this a function else use this code where you are doing other logic on the basis of this function return. If you are doing something on the basis of this function result than write all this logic inside this function callback. – Wajahat Hussain Jul 28 '19 at 18:50