0

I have given here a snap of my firebase chatrooms. The code I included here can retrieve a message of a single node. I want to search all the chatrooms with single query for new messages so that I can send a push notification. Also how to know if a message is new and which is the last message I got?

private void loadEventListFromDatabase() 
{
    DatabaseRef.userRef.child("ChatRoom").child(roomID).addChildEventListener(new ChildEventListener() {

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

            GetMessage getMessage = dataSnapshot.getValue(GetMessage.class);
            Message message = new Message(getMessage.getMessageBody(),getMessage.getCreator(),imageCode);
            recyclerViewRCV.setLayoutManager(getMyLinearLayout());
            recieveMessageList.add(message);
            recieveMsgAdapter.notifyDataSetChanged();

        }

        @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) {

        }
    });
}

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • If you consider at some point to try using [Cloud Firestore](https://firebase.google.com/docs/firestore/), here you can find a tutorial on how to create a complete and functional [Firestore Chat App](https://www.youtube.com/playlist?list=PLn2n4GESV0Ak1HiH0tTPTJXsOEy-5v9qb). – Alex Mamo Apr 08 '19 at 06:13

1 Answers1

0

Firebase Database queries operate on a list of nodes, not on a tree. If you want to get a list of all new messages across all rooms, you must have a list of all messages across all rooms.

For more on this, see:


Firebase has nothing built in to track what messages are new between two times when you attach a listener. This means you need to build it yourself.

The two common approaches are:

  • Tracking exactly what messages each user has read.
  • Tracking the latest messages that each user has read.

The latter is by far the simplest and most common. In your case you can simply keep the key of the last message the user has seen (either in the database, or in the local storage of the app), and then pass it in next time with ref.orderByKey().startAt(lastKeySeen).

For more on this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807