0

I am having some touble with the following code snipped:

mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void  onDataChange(DataSnapshot dataSnapshot) {
        size = (int) dataSnapshot.getChildrenCount();   
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});
viewHolder.setCount(size);

The size returns null but I don't understand why. I want to pass count values to recyclerview.

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81

1 Answers1

1

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
    }
});
Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • How can I transfer it to TextView which is also found in RecycleView. –  Jul 15 '17 at 18:04