Disorganized Chat messages in my Chat App using Firebase

Viewed 51

I recently added a feature to send images too along with the option to send text messages. Everything was working fine before that - messages popped as expected queried by descending time. But after I added this image sending feature whenever I scroll up or down the chat the messages get all jumbled up and I don't know why.

When I send only text:

Before Scrolling https://i.stack.imgur.com/2NMVHl.jpg

After Scrolling https://i.stack.imgur.com/2Nxpc.jpg (same)

When I send Image with text

Before Scrolling https://i.stack.imgur.com/rS6Mx.jpg

After Scrolling https://i.stack.imgur.com/OP5DK.jpg

In my code there are two places from where message(image or text) can be uploaded.

  1. For sending Image message:

Briefings - Here I upload the image to the Storage and then retrieve its URL. Then I store the URL to firestore in form of string (which I later use to download the image using Picasso) along with other message details.

            final Long currentTime = System.currentTimeMillis();
            final String time = currentTime + "";
            final StorageReference fileref = storageReference.child("Image Messages")
                    .child(uid + time);
            StorageTask uploadTask = fileref.putFile(uri);
            uploadTask.continueWithTask(new Continuation() {
                @Override
                public Object then(@NonNull Task task) throws Exception {
                    if(!task.isSuccessful()){
                        throw task.getException();
                    }
                    return fileref.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if(task.isSuccessful()){
                        Uri downloadUrl = task.getResult();
                        String myUrl = downloadUrl.toString();

                        Map<String, Object> chat = new HashMap<>();
                        chat.put("message", myUrl);
                        chat.put("time", currentTime);
                        chat.put("sender", mUser.getUid());
                        chat.put("groupId",Gid);
                        chat.put("type","image");
                        chat.put("username",preferences.getData("username"));
                        chat.put("name",preferences.getData("usernameAdded"));
                        firestore.collection("aGroups").document(Gid).collection("Chat")
                                .add(chat).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                            @Override
                            public void onSuccess(DocumentReference documentReference) {
                                showChatMessages();
                                dialog.dismiss();
                                Toast.makeText(getApplicationContext(),"Message Sent", Toast.LENGTH_SHORT).show();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
  1. For sending text message

Briefings - Here I upload the message and it's details

 Map<String, Object> chat = new HashMap<>();
                    chat.put("message", message.getText().toString());
                    chat.put("time", System.currentTimeMillis());
                    chat.put("sender", mUser.getUid());
                    chat.put("groupId",Gid);
                    chat.put("type","text");
                    chat.put("username",preferences.getData("username"));
                    chat.put("name",preferences.getData("usernameAdded"));
                    firestore.collection("aGroups").document(Gid).collection("Chat")
                            .add(chat).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            Toast.makeText(ChatInterface.this, "Message Sent", Toast.LENGTH_SHORT).show();
                            showChatMessages();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT).show();
                        }
                    });

This is where I add callbacks

private void showChatMessages() {
        firestore.collection("aGroups").document(Gid).collection("Chat")
                .orderBy("time", Query.Direction.DESCENDING)
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                if(error != null){
                    Log.d("Check", "listen failed: " + error.getMessage());
                }

                else{
                    Log.d("Check", "Snapshot worked");
                    List<ChatModel> list = new ArrayList<>();
                    list.clear();
                    for(QueryDocumentSnapshot query : value){
                    list.add(new ChatModel(
                              query.getString("groupId")
                            , query.getId()
                            , query.getString("message")
                            , query.getString("sender")
                            , query.getLong("time")
                            , query.getString("name")
                            , query.getString("username")
                            , query.getString("type")
                    ));
                }
                recycler_interface.setAdapter(new RealChatRecyclerInterface(mUser.getUid(),list));
            }}
        });
    }

I am adding my whole RealChatRecyclerInterface in this pastebin link.

1 Answers

Use holder.setIsRecyclable(false); in your RealChatRecyclerInterface

Related