ribbit
ribbit

Reputation: 1283

onAddChild of ChildEventListener fires for all existing nodes when I add the listener

I can't understand why this is happening!

I'm trying to add a listener to detect when "new" data has been added to the database. The problem is that, as soon as I add the listener, the onChildAdded method starts firing for all the existing nodes contained under the given path as if those were just added (but they were obviously already there).

What is even weirder is that the problem is occurring only with a set of already existing nodes. I tried copying the content of the problematic nodes into a new node but the new node does not seem to have this problem. I literally exported the JSON of the faulty nodes and imported into the new node, but the new one is working fine.

I'm adding a ChildEventListener like so

FirebaseDatabase.getInstance().getReference("roles/roleAdmin").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            // This should be fired only if new data is added to the
            // database under the path roles/roleAdmin,
            // but instead, as soon as the program runs the line to add the
            // ChildEventListener (above), this event starts firing for each
            // one of the already existing nodes under roles/roleAdmin
        }

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

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

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

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {}
    });

The data under the roles node looks like this

role: {
    roleAdmin: {
        name: "Admin"
    }
}

This is directly under the root level btw. There was more data under this node, but I observed that the same issue is occurring even with this little data.

As I said, it seems to be happening with some of the nodes that already existed. When I try to create a new node at the same level and give it the same exact content to see if it will have the same effect, the new node works fine.

I don't imagine this is expected behavior. Is there something I'm missing?

Upvotes: 1

Views: 168

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

I don't imagine this is expected behavior.

Yes it is. If you are using a ChildEventListener, it means your onChildAdded() method gets called for each child node immediately and then later whenever a new child is added. So according to the number of items you have, , onChildAdded() will be invoked by the same number of times and unfortunately this behaviour cannot be changed.

Upvotes: 1

Related Questions