[Solved] Code does not wait for FirebaseDatabase to be read


As Selvin commented: data is loaded from Firebase asynchronously. You can’t reliably wait for the data to become available. See Setting Singleton property value in Firebase Listener.

The solution is to move the code that needs the data from Firebase into the onDataChange in checkDataNew:

fun checkDataNew() {
    var rootRef=FirebaseDatabase.getInstance().getReference("BG Data")
    // Read from the database
    rootRef.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            var isKeyFound = false; // local variables
            var foundKey;
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            for(data:DataSnapshot in dataSnapshot.children)
            {
                var oldEvent=data.child("recentEvent").getValue().toString()
                var oldDate:String=data.child("calendarTime").getValue().toString()
                var oldEmailID:String=data.child("emailID").getValue().toString()

                if(oldEvent.equals(recentEvent) && oldDate.equals(calendarTime) && oldEmailID.equals(emailID)) {
                    foundKey = data.key.toString()
                    isKeyFound = true
                }
            }

            // TODO: process the result here
            if (isKeyFound) {
              ...
            } else {
              ...
            }
        }

        override fun onCancelled(error: DatabaseError) {
            // Failed to read value
        }
    })
}

Alternatively you can define your own callback interface, pass that into checkDataNew and invoke it from within there. For an example of this, see getContactsFromFirebase() method return an empty list.

This is a quite common question. So in addition to the links I already provided, I recommend you check out some of these:

  • can’t get values out of ondatachange method
  • ArrayList not updating inside onChildAdded function
  • Android Firebase addListenerForSingleValueEvent is not working
  • How to return dataSnapshot value as a result of a method?
  • Only load layout when firebase calls are complete
  • Android: wait for firebase valueEventListener

0

solved Code does not wait for FirebaseDatabase to be read