본문 바로가기
Android

[Android/Kotlin] firebase chat(1/2) 채팅목록 (RecyclerView)

by noddu 2022. 3. 18.
728x90
반응형

Realtime Datebase로 만든

채팅할 상대방의 Product 테이블이 다음과 같이 있다

 


●Product

 

public class Product {
    private String Pro_uid;
    private String Pro_Image;
    private String Pro_name;
    private int Pro_price;
    private String Pro_status;
    private String Pro_content;

    public Product(){}

    public Product(String Pro_uid, Uri Pro_Image, String Pro_name, int Pro_price, String Pro_status, String Pro_content) {
        this.Pro_uid = Pro_uid;
        this.Pro_Image = Pro_Image.toString();
        this.Pro_name = Pro_name;
        this.Pro_price = Pro_price;
        this.Pro_status = Pro_status;
        this.Pro_content = Pro_content;
    }

    public String getPro_uid() { return Pro_uid; }

    public void setPro_uid(String pro_uid) { Pro_uid = pro_uid; }

    public String getPro_Image() { return Pro_Image; }

    public void setPro_Image(String pro_Image) { Pro_Image = pro_Image; }

    public String getPro_name() { return Pro_name; }

    public void setPro_name(String pro_name) { Pro_name = pro_name; }

    public int getPro_price() { return Pro_price; }

    public void setPro_price(int pro_price) { Pro_price = pro_price; }

    public String getPro_status() { return Pro_status; }

    public void setPro_status(String pro_status) { Pro_status = pro_status; }

    public String getPro_content() { return Pro_content; }

    public void setPro_content(String pro_content) { Pro_content = pro_content; }

    @Override
    public String toString() {
        return "Product{" +
                "Pro_uid='" + Pro_uid + '\'' +
                ", Pro_Image='" + Pro_Image + '\'' +
                ", Pro_name='" + Pro_name + '\'' +
                ", Pro_price=" + Pro_price +
                ", Pro_status='" + Pro_status + '\'' +
                ", Pro_content='" + Pro_content + '\'' +
                '}';
    }

Product는 java로 작성했다


 

●fragment_chatroom.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/chatroom_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

다음과 같이 recyclerview를 사용하겠다


 

●chatroom_list.xml

<LinearLayout
    android:id="@+id/chatroom_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/chatroom_userImg"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_margin="10dp"
            android:src="@mipmap/ic_launcher"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/chatroom_userName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="이름"
                android:textSize="16sp"
                android:textStyle="bold"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"/>


            <TextView
                android:id="@+id/chatroom_recentMessage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="메세지"
                android:textSize="14sp"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"/>

            <TextView
                android:id="@+id/chatroom_recentTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="시간"
                android:textSize="14sp"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

recyclerview에 들어갈 item은 Product 테이블의 해당 사진, 이름

그 후에 구현할 메세지와 메세지를 보낸 시간이 보이도록 작성했다

 

 


●fragment_chatroom.xml

private var database: FirebaseDatabase? = null
private var databaseReference: DatabaseReference? = null
private var arrayList: ArrayList<Product>? = null

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    chatroombinding = FragmentChatroomBinding.inflate(inflater, container, false)
    val view = chatroombinding!!.root
    chatroombinding!!.chatroomRecycler.layoutManager = LinearLayoutManager(context)

    return view

onCreateView에서 recyclerview의 layoutManager를 설정해주고

arrayList도 미리 정의해뒀다

 

 

database = FirebaseDatabase.getInstance() // 파이어 데이터베이스 연동

databaseReference = database!!.getReference("Product") // 파이어베이스 Product 테이블 연결

    databaseReference!!.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            // 파이어 베이스 데이터 받아옴

            arrayList!!.clear() //배열리스트 초기화

            for (snapshot1 in snapshot.children) {
                val product = snapshot1.getValue(
                    Product::class.java
                )
                arrayList!!.add(product!!)

                chatroomAdapter.getchatroomAdapter(arrayList!!)
                chatroombinding!!.chatroomRecycler.adapter = chatroomAdapter //setAdapter
            }
        }
        override fun onCancelled(error: DatabaseError) {
            Log.e("chatroom_data-error", error.toException().toString())
        }
    })

Product 테이블과 연결하고 모든 값들을 arrayList에 집어넣는다

그리고 어댑터에서 getchatroomAdapter함수를 이용해 arrayList를 주고 어댑터와 연결한다

 


●ChatroomAdapter

class ChatroomAdapter : RecyclerView.Adapter<ChatroomAdapter.ViewHolder> (){

    private var arrayList: ArrayList<Product> = arrayListOf()

    fun getchatroomAdapter(chatroomDataset : ArrayList<Product>) {
        this.arrayList = chatroomDataset
        Log.d("array_data", arrayList.toString())
    }
    
    
    D/array_data: [Product{Pro_uid='6xOHCf5LYSS3a7aUH2d7u8XLPZw2', Pro_Image='content://media/external/images/media/3893', Pro_name='uidtest', Pro_price=123, Pro_status='aaa', Pro_content='aa'}, Product{Pro_uid='6xOHCf5LYSS3a7aUH2d7u8XLPZw2', Pro_Image='content://media/external/images/media/3888', Pro_name='sss', Pro_price=123, Pro_status='sss', Pro_content='sss'}, Product{Pro_uid='a5zLnHLwDWQ2zyDGXWAe3fZJ0xm2', Pro_Image='content://media/external/images/media/3889', Pro_name='test', Pro_price=123, Pro_status='test', Pro_content='test'}]

위에서 getchatroomAdapter함수로 넘어온 arrayList를 받는다

Log가 잘 출력되는걸 볼 수 있다

 

 

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val binding = ChatroomListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    return ViewHolder(binding)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.bind(arrayList[position])
}

override fun getItemCount(): Int {
    return arrayList.size
}

ViewHolder를 제외한 나머지 함수는 건들이지 않았다

 

class ViewHolder(private val binding: ChatroomListBinding) : RecyclerView.ViewHolder(binding.root) {

    fun bind(data: Product) {

        Glide.with(itemView).load(data.pro_Image).into(binding.chatroomUserImg)
            binding.chatroomUserName.text = data.pro_uid
            binding.chatroomRecentMessage.text = data.pro_name

        var database = FirebaseDatabase.getInstance().getReference("Chatroom").child("${data.pro_uid}").child(
            "${data.pro_name}")
        Log.d("database_data", database.toString())

            database.addValueEventListener(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {

                    for (snapshot1 in snapshot.children) {
                        val chat = snapshot1.getValue(Chat::class.java)
                        Log.d(TAG, "onDataChange_data4:" + snapshot1.value)

                        Log.d("chat2_data", chat.toString())
                        binding.chatroomRecentTime.text = "RecentMessage: ${chat.chat_userMessage}"
                    }
                }

                override fun onCancelled(error: DatabaseError) {
                }
            })

        itemView.setOnClickListener{
            Intent(itemView.context, ChatActivity::class.java).apply {
                putExtra("Chat_Uid","${data.pro_uid}")
                putExtra("Chat_ProductName","${data.pro_name}")
            }.run { itemView.context.startActivity(this) }
        }
    }


}

uid, name, img는 Product의 데이터를 가져오면 된다

 

 

var database = FirebaseDatabase.getInstance().getReference("Chatroom").child(data.pro_uid).child(data.pro_name)

하지만 그 상대 uid를 가져와 Chatroom 테이블에 채팅내용을 가져오는 부분은

Chatroom테이블 생성부터 있어야되기 때문에 (2/2) 채팅방 만들기를 참고해야한다

 

반응형