Reputation: 577
i've a problem with the FirebaseDatabase. I want to read the count of childs from a datebase reference. And I want to do this 5 times. So I created 5 SingleEventListeners and set the value, if there's no user for this date. (I hope you understand, what I want to do :D)
while (counter<5) {
... We create a new date and username here. We have to do this 5 times
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!(dataSnapshot.child(finalDate).hasChild(username)))
myRef.child(finalDate).child(username).setValue(true);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
counter++;
}
try { //TODO Synchronisation is not given without that block
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
...
...
...
myRef.child(chosenDate).child(username).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
participate.setChecked((Boolean) dataSnapshot.getValue());
}
Here we get a Nullpointer Exception, if we don't wait for receiving the date. What can I do instead of the use of sleep(), which is really bad :(
Upvotes: 0
Views: 94
Reputation: 598728
Thread.sleep()
is hardly ever the solution you want. In this case, since you know how many items you're loading, you can just count the number of items that have loaded (or definitely failed to load):
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!(dataSnapshot.child(finalDate).hasChild(username)))
myRef.child(finalDate).child(username).setValue(true);
counter++;
if (counter == 5) {
// TODO: whatever you want to do after all items have loaded
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
counter++;
if (counter == 5) {
// TODO: whatever you want to do after all items have loaded
}
}
});
Upvotes: 1