每当应用程序最小化时,RecyclerView就会复制值

时间:2019-01-21 16:29:07

标签: android firebase android-recyclerview messaging

我正在使用Android中的Firebase和RecyclerView构建一个简单的聊天应用程序。我有一个按钮可以从图库发送图像消息,还有一个发送按钮可以发送文本消息。问题是,当我发送图像消息时,该消息被复制,此后,无论我发送什么,该消息都被复制。无论如何,当我返回并再次进入消息活动时,该消息会正确显示。我不明白是什么问题。也许列表每次都在复制项目。此外,如果我最小化应用程序,然后发送消息,则消息将变成三倍,四倍等等。

这是我的代码:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        reference = FirebaseDatabase.getInstance().getReference().child(getString(R.string.node_profile_settings));
        mRootref = FirebaseDatabase.getInstance().getReference();
        chatReference = FirebaseDatabase.getInstance().getReference().child(getString(R.string.node_chat));
        userReference = FirebaseDatabase.getInstance().getReference().child(getString(R.string.node_users));
        messageUserId = getIntent().getStringExtra("message_user_id");

        mMessageUsernameTB = findViewById(R.id.messageUsername);
        mBackArrow = findViewById(R.id.backArrow);
        mPlus = findViewById(R.id.ivPlus);
        mSendMessageBtn = findViewById(R.id.ivSendMessageBtn);
        mTextMessageInput = findViewById(R.id.etSendMessage);
        mOnlineStatus = findViewById(R.id.onlineStatus);
        mProgressBar = findViewById(R.id.progressBar);
        mRefreshLayout = findViewById(R.id.message_swipe_layout);
        mMessageUserLastSeen = findViewById(R.id.messageUserLastseen);
        mMessageUserProfileImage = findViewById(R.id.messageUserProfilePhoto);
        mRecyclerMessageView = findViewById(R.id.messages_list);

        messageListAdapter = new MessageListAdapter(messagesList);
        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerMessageView.setHasFixedSize(true);
        mRecyclerMessageView.setLayoutManager(linearLayoutManager);
        mRecyclerMessageView.setAdapter(messageListAdapter);
        mImageStorage = FirebaseStorage.getInstance().getReference();

        reference.child(messageUserId).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String messageUsername = dataSnapshot.child(getString(R.string.field_name)).getValue().toString();
                String messageUserProfilePhoto = dataSnapshot.child(getString(R.string.field_profile_image)).getValue().toString();
                mMessageUsernameTB.setText(messageUsername);
                Glide.with(getApplicationContext()).applyDefaultRequestOptions(new RequestOptions()
                        .placeholder(R.drawable.profilephoto)).load(messageUserProfilePhoto).into(mMessageUserProfileImage);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        userReference.child(messageUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Log.d(TAG, "onDataChange: retrieving online status");

                String online = dataSnapshot.child("online").getValue().toString();
                if(online.equals("true")){
                    mMessageUserLastSeen.setText("Online");
                    mOnlineStatus.setVisibility(View.VISIBLE);
                }else{
                    GetTimeAgo getTimeAgo = new GetTimeAgo();
                    long lastTime = Long.parseLong(online);
                    String lastSeen = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
                    mOnlineStatus.setVisibility(View.INVISIBLE);
                    mMessageUserLastSeen.setText(lastSeen);
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

        chatReference.child(currentUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(!dataSnapshot.hasChild(messageUserId)){
                    Map chatAddMap = new HashMap();
                    chatAddMap.put("seen", false);
                    chatAddMap.put("timestamp", ServerValue.TIMESTAMP);

                    Map chatUserMap = new HashMap();
                    chatUserMap.put("chats/" + currentUserId + "/" + messageUserId, chatAddMap);
                    chatUserMap.put("chats/" + messageUserId + "/" + currentUserId, chatAddMap);

                    mRootref.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
                        @Override
                        public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
                            if(databaseError!=null){
                                Log.d(TAG, "onComplete: " +  databaseError.getMessage().toString());
                            }
                        }
                    });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        mBackArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: Navigating back");
                finish();
            }
        });

        mSendMessageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: Sending message");
                sendMessage();
            }
        });

        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //CODE TO LOAD MORE MESSAGES
                mRefreshLayout.setRefreshing(false);

            }
        });

        mPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(galleryIntent, GALLERY_PICK);
                //mCurrent_page = 1;
                messagesList.clear();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {

            mProgressBar.setVisibility(View.VISIBLE);
            Uri imageUri = data.getData();

            final String current_user_ref = "messages/" + currentUserId + "/" + messageUserId;
            final String chat_user_ref = "messages/" + messageUserId + "/" + currentUserId;

            DatabaseReference user_message_push = mRootref.child("messages")
                    .child(currentUserId).child(messageUserId).push();

            final String push_id = user_message_push.getKey();


            final StorageReference filepath = mImageStorage.child("message_images").child(push_id + ".jpg");

            filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            Uri download_url = uri;
                            String downloadUrl = download_url.toString();

                            Map messageMap = new HashMap();
                            messageMap.put("message", downloadUrl);
                            messageMap.put("seen", false);
                            messageMap.put("type", "image");
                            messageMap.put("time", ServerValue.TIMESTAMP);
                            messageMap.put("from", currentUserId);

                            Map messageUserMap = new HashMap();
                            messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
                            messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);

                            mTextMessageInput.setText("");
                            mProgressBar.setVisibility(View.GONE);

                            mRootref.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
                                @Override
                                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                                    if (databaseError != null) {

                                        Log.d("CHAT_LOG", databaseError.getMessage().toString());

                                    }

                                }
                            });
                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, "onFailure: Photo sending Failed");

                }
            });
        }
    }

    //SENDING MESSAGE
    private void sendMessage() {
        Log.d(TAG, "sendMessage: Sending message to the user");
        String message = mTextMessageInput.getText().toString();
        if (!TextUtils.isEmpty(message)) {

            String current_user_ref = "messages/" + currentUserId + "/" + messageUserId;
            String chat_user_ref = "messages/" + messageUserId + "/" + currentUserId;

            DatabaseReference user_message_push = mRootref.child("messages").child(currentUserId)
                    .child(messageUserId).push();

            String push_id = user_message_push.getKey();

            Map messageMap = new HashMap();
            messageMap.put("message", message);
            messageMap.put("seen", false);
            messageMap.put("type", "text");
            messageMap.put("time", ServerValue.TIMESTAMP);
            messageMap.put("from", currentUserId);

            Map messageUserMap = new HashMap();
            messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
            messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);

            mTextMessageInput.setText("");

            mRootref.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                    if(databaseError != null){

                        Log.d("CHAT_LOG", databaseError.getMessage().toString());

                    }
                }
            });

        }else if(TextUtils.isEmpty(message))
        {
            Toast.makeText(this, "Enter Message first !", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadMessages(){

        DatabaseReference messageRef = mRootref.child("messages").child(currentUserId)
                .child(messageUserId);
        Query messageQuery = messageRef;
        messageQuery.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Messages messages = dataSnapshot.getValue(Messages.class);
                messagesList.add(messages);
                messageListAdapter.notifyDataSetChanged();

                mRecyclerMessageView.scrollToPosition(messagesList.size()-1);
            }

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

            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                userReference.child(currentUserId).child("online").setValue("true"); // yourMethod();
            }
        }, 2000);
        messagesList.clear();
        loadMessages();
    }

    @Override
    public void onStop() {
        super.onStop();
            userReference.child(currentUserId).child("online").setValue(ServerValue.TIMESTAMP);
        }

public class MessageListAdapter extends RecyclerView.Adapter<MessageListAdapter.MessageViewHolder> {
    private static final String TAG = "MessageListAdapter";

    //Firebase
    private FirebaseAuth mAuth;
    private DatabaseReference reference;

    private List<Messages> userMessagesList;

    public MessageListAdapter(List<Messages> userMessagesList) {
        this.userMessagesList = userMessagesList;
    }

    public class MessageViewHolder extends RecyclerView.ViewHolder{

        private TextView mSenderMessage, mRecieverMessage;
        private CardView mSenderImageCardView, mRecieverImageCardView;
        private ImageView mSenderImageMessage, mRecieverImageMessage;
        private ProgressBar mProgressBarReciever, mProgressBarSender;

        public MessageViewHolder(View itemView) {
            super(itemView);

            mSenderMessage = itemView.findViewById(R.id.tvSenderMessage);
            mRecieverMessage = itemView.findViewById(R.id.tvRecieverMessage);
            mSenderImageCardView = itemView.findViewById(R.id.messageImageSenderCardview);
            mRecieverImageCardView = itemView.findViewById(R.id.messageImageRecieverCardview);
            mSenderImageMessage = itemView.findViewById(R.id.ivSenderImageMessage);
            mRecieverImageMessage = itemView.findViewById(R.id.ivRecieverImageMessage);
            mProgressBarReciever = itemView.findViewById(R.id.progressBarReciever);
            mProgressBarSender = itemView.findViewById(R.id.progressBarSender);
        }
    }

    @NonNull
    @Override
    public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        mAuth = FirebaseAuth.getInstance();
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_messages_list, parent, false);
        return new MessageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {

        String messageSenderId = mAuth.getCurrentUser().getUid();
        Messages messages = userMessagesList.get(position);

        String fromUserId = messages.getFrom();
        String fromMessageType = messages.getType();

        reference = FirebaseDatabase.getInstance().getReference().child("users").child(fromUserId);

        if(fromMessageType.equals("text")){
            holder.mRecieverMessage.setVisibility(View.GONE);
            holder.mSenderMessage.setVisibility(View.GONE);
            holder.mSenderImageCardView.setVisibility(View.GONE);
            holder.mRecieverImageCardView.setVisibility(View.GONE);

            if(fromUserId.equals(messageSenderId)){
                holder.mSenderMessage.setVisibility(View.VISIBLE);
                holder.mSenderMessage.setBackgroundResource(R.drawable.sender_message_layout);
                holder.mSenderMessage.setTextColor(Color.WHITE);
                holder.mSenderMessage.setText(messages.getMessage());
            }else {
                holder.mRecieverMessage.setVisibility(View.VISIBLE);
                holder.mRecieverMessage.setBackgroundResource(R.drawable.reciever_message_layout);
                holder.mRecieverMessage.setTextColor(Color.BLACK);
                holder.mRecieverMessage.setText(messages.getMessage());
            }
        } else if(fromMessageType.equals("image")){
            holder.mRecieverMessage.setVisibility(View.GONE);
            holder.mSenderMessage.setVisibility(View.GONE);
            holder.mSenderImageCardView.setVisibility(View.GONE);
            holder.mRecieverImageCardView.setVisibility(View.GONE);

            if(fromUserId.equals(messageSenderId)){
                holder.mSenderImageCardView.setVisibility(View.VISIBLE);
                holder.mProgressBarSender.setVisibility(View.VISIBLE);
                Glide.with(holder.mSenderImageCardView.getContext())
                        .applyDefaultRequestOptions(new RequestOptions()
                                .placeholder(R.drawable.profilephoto)).load(messages.getMessage()).into(holder.mSenderImageMessage);
                holder.mProgressBarSender.setVisibility(View.GONE);

            }else {
                holder.mRecieverImageCardView.setVisibility(View.VISIBLE);
                holder.mProgressBarReciever.setVisibility(View.VISIBLE);
                Glide.with(holder.mRecieverImageCardView.getContext())
                        .applyDefaultRequestOptions(new RequestOptions()
                                .placeholder(R.drawable.profilephoto)).load(messages.getMessage()).into(holder.mRecieverImageMessage);
                holder.mProgressBarReciever.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public int getItemCount() {
        return userMessagesList.size();
    }

}

0 个答案:

没有答案