lape.bthe
lape.bthe

Reputation: 31

Firestore| RecyclerView not sorting or updating in realtime

I have a ChatActivity and I can successfully send messages between two users. I want to sort the messages with a timestamp value (like your regular chat application). I have called orderBy() but the messages still aren't sorted. This is my code in my activity's onCreate() method:

     Query query = currentUserRef.orderBy("time", Query.Direction.ASCENDING);
            FirestoreRecyclerOptions<Messages> options = new FirestoreRecyclerOptions.Builder<Messages>().setQuery(query, Messages.class).build();
            mAdapter = new MessagesAdapter(options,messagesList);
            mLinearLayout = new LinearLayoutManager(this);
            mMessagesList.setHasFixedSize(true);
            mMessagesList.setLayoutManager(mLinearLayout);
            mMessagesList.setAdapter(mAdapter);
        }
  private void sendMessage() {
        String message = txtMessage.getText().toString();
        if (!TextUtils.isEmpty(message)) {
            Map messageMap = new HashMap();
            messageMap.put("messages", message);
            messageMap.put("type", "text");
            messageMap.put("time", FieldValue.serverTimestamp());
            messageMap.put("from", mCurrentID);
            chat_user_ref.add(messageMap).addOnSuccessListener(documentReference -> currentUserRef.add(messageMap).addOnSuccessListener(documentReference1 -> txtMessage.getText().clear()));
            mAdapter.notifyDataSetChanged();
            mMessagesList.scrollToPosition(messagesList.size());
        }

I've tried passing the RecyclerView as a parameter to my adapter and then try to call notifyDataSetChanged() in onBindViewHolder() but I can't do that.

I want the messages to be sorted on the chat screen (from oldest to newest). And I want the recyclerview to update when a new message has been sent.

Upvotes: 0

Views: 384

Answers (1)

codeman
codeman

Reputation: 144

I experienced the same problem when I was developing my chat app. Setting the following attribute on the layout manager solved it for me:

Query query = currentUserRef.orderBy("time", Query.Direction.DESCENDING);
mLinearLayout.setReverseLayout(true);

Upvotes: 1

Related Questions