user8312867
user8312867

Reputation:

android - Firebase return null value from datasnapshot Why?

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.

Upvotes: 0

Views: 690

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

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
    }
});

Upvotes: 1

Related Questions