Java – How do I pass the onChildAdded condition in the ChildEventListener after the first call?

How do I pass the onChildAdded condition in the ChildEventListener after the first call?… here is a solution to the problem.

How do I pass the onChildAdded condition in the ChildEventListener after the first call?

I use firebase ChildEventListner for the chat application.
In this application, I pass a condition in onChildAdded, i.e. if the message senderId adds a new child than plays a sound in the activity.
Below is my code.

rootRef.child("Messages").child(MessageSenderId).child(MessageReceiverId).addChildEventListener(new ChildEventListener()
@Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s)
            {
                Messages messages=dataSnapshot.getValue(Messages.class);
                messageslist.add(messages);
                messagesAdapter.notifyDataSetChanged();
                messageList.smoothScrollToPosition(messageList.getAdapter().getItemCount());

if (messages.from.equals(MessageSenderId))
                {
                    MediaPlayer IncomingMessageSound=MediaPlayer.create(MessageActivity.this,R.raw.incoming_message_sound);
                    IncomingMessageSound.start();
                }
            }

But it works like work, when I go to the message activity, the total number of sounds played is no. The child added by the senderId time. This means that if the message is received 15 times, the sound plays 15 times when the activity starts. After that there was no sound.

So my question is how to pass the appropriate condition when a new node is added by senderId than playing a sound means playing a sound when receiving a message (not a notification sound).

Solution

This basically comes down to knowing if the user has already seen a particular message. Or to be more precise: if the user hasn’t seen any messages yet, because you might only want to play one sound, even if there are multiple new messages.

See also answer I gave in an #AskFirebase video, and the previous answer: Android Firebase New Message Query .

Related Problems and Solutions