如何在 android studio 的聊天应用程序中显示来自接收者的消息?

Posted

技术标签:

【中文标题】如何在 android studio 的聊天应用程序中显示来自接收者的消息?【英文标题】:How can i display the message from receiver in an chat application in android studio? 【发布时间】:2020-01-23 19:16:31 【问题描述】:

我们使用 Firebase 编写了一个聊天应用程序,其中发件人的消息将显示在右侧,收件人的消息将显示在左侧。

如果您使用发送按钮发送消息,发件人的消息将正确显示在右侧。

很遗憾,发送给接收者的消息没有显示在左侧。

我们的 Recyclerview java 代码是这样的:

package com.example.myapplicationsonet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Message_recyclerview extends AppCompatActivity 

    TextView tvUsername;
    ImageButton ibtnSend;
    EditText etMessage;

    FirebaseUser fuser;
    DatabaseReference databaseReference;

    MessageAdapter messageAdapter;
    List<message_helperclass> mChat;

    RecyclerView recyclerView;

    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_message_recyclerview );

        recyclerView = (RecyclerView) findViewById(R.id.rvmessage);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(linearLayoutManager);

        tvUsername = (TextView) findViewById(R.id.textView_message_username);
        etMessage = (EditText) findViewById(R.id.messagebox);
        ibtnSend = (ImageButton) findViewById(R.id.button_send);

        intent = getIntent();
        final String username = intent.getStringExtra("username");
        fuser = FirebaseAuth.getInstance().getCurrentUser();

        fuser = FirebaseAuth.getInstance().getCurrentUser();
        databaseReference = FirebaseDatabase.getInstance().getReference("User").child(username);

        databaseReference.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) 

                tvUsername.setText(username);

                readMessages(fuser.getUid(), username);
            

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 

            
        );

        ibtnSend.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                String msg = etMessage.getText().toString();
                if (!msg.equals(""))
                    sendMessage(fuser.getUid(), username, msg);
                else 
                    Toast.makeText(Message_recyclerview.this, "Du kannst keine leeren Nachrichten versenden", Toast.LENGTH_LONG).show();
                


                etMessage.setText("");
            
        );

    

    private void sendMessage(String sender, String receiver, String message )

        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("sender", sender);
        hashMap.put("receiver", receiver);
        hashMap.put("message", message);

        databaseReference.child("Chats").push().setValue(hashMap);
    

    private void readMessages(final String myid, final String username)
        mChat = new ArrayList<>();

        databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
        databaseReference.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
                mChat.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren())
                    message_helperclass chat = snapshot.getValue(message_helperclass.class);
                    if (chat.getReceiver().equals(myid) && chat.getSender().equals(username) ||
                    chat.getReceiver().equals(username) && chat.getSender().equals(myid))
                        mChat.add(chat);
                    

                    messageAdapter = new MessageAdapter(Message_recyclerview.this, mChat);
                    recyclerView.setAdapter(messageAdapter);
                
            

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 

            
        );
    

这是我们的适配器类:

package com.example.myapplicationsonet;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> 

    public static final int MSG_TYPE_LEFT = 0;
    public static final int MSG_TYPE_RIGHT = 1;

    private Context mContext;
    private List<message_helperclass> mChat;

    FirebaseUser fUser;

    public MessageAdapter(Context mContext, List<message_helperclass> mChat)
        this.mChat = mChat;
        this.mContext = mContext;
    

    @NonNull
    @Override
    public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 

        if (viewType == MSG_TYPE_RIGHT)
            View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
            return new MessageAdapter.ViewHolder(view);
         else 
            View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
            return new MessageAdapter.ViewHolder(view);
        
    

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

        message_helperclass chat = mChat.get(position);

        holder.show_message.setText(chat.getMessage());

    

    @Override
    public int getItemCount() 
        return mChat.size();
    

    public class ViewHolder extends RecyclerView.ViewHolder 

        public TextView show_message;

        public ViewHolder(@NonNull View itemView) 
            super(itemView);

            show_message = itemView.findViewById(R.id.show_message);
        
    

    @Override
    public int getItemViewType(int position) 
        fUser = FirebaseAuth.getInstance().getCurrentUser();
        if (mChat.get(position).getSender().equals(fUser.getUid()))
            return MSG_TYPE_RIGHT;
         else 
            return MSG_TYPE_LEFT;
        

    

很遗憾,我们找不到左侧不显示收件人消息的错误。

我希望你能帮助我们。这很重要。

谢谢!

【问题讨论】:

【参考方案1】:

无法评论,但您检查过您的chat_item_rightchat_item_left XML 文件吗?您的代码显示正确,因此可能存在错误。

【讨论】:

以上是关于如何在 android studio 的聊天应用程序中显示来自接收者的消息?的主要内容,如果未能解决你的问题,请参考以下文章

Android IPC机制用Socket实现跨进程聊天程序

如何在 android studio 中包含应用内图标选择器?

协程主体未涵盖在单元测试代码覆盖范围内 - Android Studio

Android Studio - 提示使用任何可用的应用程序打开下载的文件

Android Studio创建AIDL文件并实现进程间通讯

如何使用 asmack 在 android 中创建多用户聊天应用程序