Saad Zahoor
Saad Zahoor

Reputation: 146

Firebase database: ChildEventListener is firing multiple times

On application start the ChildEventListener is getting fired the amount of child present in the firebase database. For instance, if I have already 3 children present in the database, the listener will get invoke 3 times when I start my application. s I have defined the code for the listener in my service class and I am starting the service from my Splash class.

From SplashScreen.class

startService(new Intent(this , BackgroundService.class));

From BackgroundService.class

listenToJob() method, is in onStartCommand() method of Service

 private void listenToJob (){


        String collectionName = "rideRequest";
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference(collectionName);


        ChildEventListener childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

             
                Toast.makeText(BackgroundService.this, "Hey, new child is added.", Toast.LENGTH_SHORT).show();
                OnChildCreated(snapshot);
            }



            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };

        myRef.addChildEventListener(childEventListener);

    }

I don't what cause this behavior. Isn't onChildAdded() method should only be invoked when a new child is added to the database? I have 3 children already present in the database and when I open my app this onChildAdded() method is getting invoke 3 times.

I want this method to fire up only when child is added to the database!

Upvotes: 1

Views: 973

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

According to the Firebase documentation on listening for child events, the onChildAdded:

is triggered once for each existing child and then again every time a new child is added to the specified path.

So what you're seeing is the expected behavior.

If you want to only be informed of new children, you need to have something that defines when a child is "new". For example, if you're using Firebase's built-in push() method to generate the child nodes, you can use the keys that generates to only get child nodes that are generated after you start listening with:

String key = myRef.push().getKey()
myRef.orderByKey().startAt(key).addChildEventListener(childEventListener);

Upvotes: 2

Related Questions