I am having some touble with the following code snipped:
mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
publi
The data is loaded from Firebase asynchronously. This means that the order in which your code is execute is not what you're likely expecting. You can most easily see this by adding a few log statements to the code:
System.out.println("Before addListenerForSingleValueEvent");
mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("In onDataChange");
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
System.out.println("After addListenerForSingleValueEvent");
The output of this is:
Before addListenerForSingleValueEvent
After addListenerForSingleValueEvent
In onDataChange
This is probably not what you expected! The data is loaded from Firebase asynchronously. And instead of waiting for it to return (which would cause an "Application Not Responding" dialog), the method continues. Then when the data is available, your onDataChange
is invoked.
To make the program work, you need to move the code that needs the data into the onDataChange
method:
mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("size ="+dataSnapshot.getChildrenCount());
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});