1

mMessages is a method. I have an SQLite table, and every time a new message is received I want to add +1 to a column. That's what the mMessages() method does, but instead of adding +1 every time a new child is added, it adds all the existing children every time I open the activity.

Say, support in table, the value is 10 and I have 5 children in the RecyclerView, and I open it, and before I even receive a new child, the table gets +5 added because there are 5 existing children.

I don't want this to happen, but I want +1 to be added only when a new child is added. How can I achieve this?

@Override
protected void onBindViewHolder(@NonNull final Chat.MessagesViewHolder holder, final int position, @NonNull final MessagesHelper model) {
    holder.setMessage(model.getMessage());

    final String userId = getRef(position).getKey();
    final DatabaseReference mTimeReference = FirebaseDatabase.getInstance().getReference().child("Messages").child(MessageSenderId).child(MessageRecieverId);
    Query messageQuery = mTimeReference.limitToLast(10);
    messageQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            MessagesHelper message = dataSnapshot.getValue(MessagesHelper.class);

            mMessages();

        }


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

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }

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

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51

1 Answers1

0

Firebase performs what is known as state synchronization: it synchronizes the data of what you listen to. To only get new data, you'll need to listen for only new data.

One way to do that is by having a timestamp and each item, and query for items with a timestamp after the time that you attach the listeners.

Another way is to limit to only the last item.

But both would also affect the messages that you show.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • the link u provided is of kotlin and can u show me how to achieve that using timestamp please –  Nov 20 '18 at 05:00