Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to get the number of children of a node without loading all the node data in Android?

My datastructure (userdetails)

-KCV32vWQECRlMvlgkGO
    Name: "asdf"
    Phoneid: "1zlkflakfhkf0e8"
    Phoneno: "9478567899"
-KCV3s-lwv5i-VvFBaxq
    Name: "asas"
    Phoneid: "1c584jbascjasc8"
    Phoneno: "9999999999"

My method

queryRef.addChildEventListener(new ChildEventListener() {

    public void onCancelled(FirebaseError arg0) {
        // TODO Auto-generated method stub
    }

    public void onChildAdded(DataSnapshot arg0, String arg1) {
        // TODO Auto-generated method stub
        System.out.println("Size "+arg0.getChildrenCount());
    }

How to get a count of 2? I am getting 3 two times because each time it goes inside and get child separately.

like image 281
Vanitha Avatar asked Sep 23 '22 03:09

Vanitha


1 Answers

The problem is that the snapshot that a child_added event gives you is the new child data. So getChildrenCount() counts how many properties (children) the new child has (and it has 3).

To do what you want you should add a ValueEventListener event like so:

queryRef.addValueEventListener(new ValueEventListener() {
    public void onCancelled(FirebaseError arg0) {
    }

    public void onDataChanged(DataSnapshot arg0, String arg1) {
        System.out.println("Size "+arg0.getChildrenCount());
    }
});

This should return all the children at queryRef location every time the value changes (e.g new child).

Tell me if this works as I can't try it myself.

like image 178
Pierre C. Avatar answered Nov 15 '22 11:11

Pierre C.