gikarasojo kinene gikarasojo kinene - 24 days ago 8
Android Question

How to know number of items returned by query in Firebase

I have this query in my Firebase

mDataBase = FirebaseDatabase.getInstance().getReference("animals);
query = mDataBase.orderByChild("height").limitToLast(20);
query.addChildEventListener(new AnimalsEventListener());


My listener

private class AnimalsEventListener implements ChildEventListener{

private AnimalsEventListener(){
}

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Animals details = dataSnapshot.getValue(Animals.class);
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
}


How can I get the size of all animals that matched the query before working on dataSnapShot? sometimes they can be less than 20;

Answer

It's not possible to know children count using ChildEventListener, use ValueEventListener instead.

public class AnimalsEventListener implements ValueEventListener {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.getChildrenCount() == 20) {
            for (DataSnapshot dataSnapshotEntry : dataSnapshot.getChildren()) {
                Animals details = dataSnapshotEntry.getValue(Animals.class);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
}

To attach this listener, use addValueEventListener() method

query.addValueEventListener(new AnimalsEventListener());
Comments