Android Studio

Android - 방명록 작성 (Firestore Database)

내손은개발 🐾 2024. 2. 29. 22:14
 

Firebase - Firestore Database 사용

1) Firebase 앱 등록 / gradle 앱 등록 / implementation 방식은 생략 더보기 //firebase implementation("com.google.firebase:firebase-auth-ktx") implementation("com.google.firebase:firebase-firestore-ktx") implementation(platform("com.google.fireb

rlawog.tistory.com

위에 글에서 프로젝트 등록을 끝냈다면

 

1) RecyclerView 생성

더보기

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/theme_layout_color"
tools:context=".CommentActivity">

<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:text="방명록"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="@id/line"
app:layout_constraintTop_toTopOf="parent" />

<View
android:id="@+id/line"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="35dp"
android:background="@color/grey"
app:layout_constraintStart_toStartOf="@id/titleTextView"
app:layout_constraintTop_toBottomOf="@id/titleTextView" />

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/commentRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/line"
app:layout_constraintStart_toStartOf="@id/line"
app:layout_constraintTop_toTopOf="@id/line" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:backgroundTint="@color/grey"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:src="@drawable/icon_add" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:backgroundTint="#22C8E4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@id/addButton"
android:src="@drawable/icon_reset" />








</androidx.constraintlayout.widget.ConstraintLayout>

2) 해당 item layout 설정

 

3) Firestore 필드 이름과 같이 recyclerView Item 생성

 - firestore의 타입과 같게 생성한다.

//ItemLayout.kt
class ItemLayout(val name: String, val comment:String)

 

4) adapter 생성

//ArticleAdapter.kt
class ArticleAdapter(private val itemList: ArrayList<ItemLayout>) : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.comment_item, parent, false)
        return ViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.name.text = itemList[position].name
        holder.comment.text = itemList[position].comment
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val name: TextView = itemView.findViewById(R.id.list_tv_name)
        val comment: TextView = itemView.findViewById(R.id.list_tv_number)
    }
}

 

 

5) 해당 코드 작성

 

package com.example.kotlin_ot_project_i

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.setPadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.kotlin_ot_project_i.data.ArticleAdapter
import com.example.kotlin_ot_project_i.data.ItemLayout
import com.example.kotlin_ot_project_i.databinding.ActivityCommentBinding
import com.google.firebase.firestore.FirebaseFirestore

class CommentActivity : AppCompatActivity() {
    private lateinit var binding: ActivityCommentBinding
    val db = FirebaseFirestore.getInstance()
    val itemList = arrayListOf<ItemLayout>()
    val adapter = ArticleAdapter(itemList)


    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityCommentBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        val view = binding.root
        setContentView(view)

        val popupMenu = PopupMenu(applicationContext,binding.creditBar.menuBtn)
        menuInflater.inflate(R.menu.menu_pop_up, popupMenu.menu)
        toolbarFun(binding.creditBar.menuBtn,this ,popupMenu, this, 6)
        returnFun(binding.creditBar.returnBtn, this)

        binding.commentRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.commentRecyclerView.adapter = adapter
        commentUpdate()

        binding.resetButton.setOnClickListener {
            commentUpdate()
        }
        binding.addButton.setOnClickListener {
            commentAdd()
        }
    }
    private fun commentUpdate(){
        db.collection("articles")
            .get()
            .addOnSuccessListener { result ->
                itemList.clear()
                for (document in result) {
                    val item = ItemLayout(document["name"] as String, document["comment"] as String)
                    itemList.add(item)
                }
                adapter.notifyDataSetChanged() // recyclerVIew 갱신
            }
            .addOnFailureListener { exception ->
                showToast(this, "불러오기 실패")
                Log.w("CommentActivity", "Error for: $exception")
            }
    }

    private fun commentAdd() {
        val builder = AlertDialog.Builder(this)

        val tvName = TextView(this)
        tvName.text = "이름"
        val tvComment = TextView(this)
        tvComment.text = "내용"
        val etName = EditText(this)
        etName.maxLines = 1
        val etComment = EditText(this)
        etName.maxLines = 1
        val mLayout = LinearLayout(this)
        mLayout.orientation = LinearLayout.VERTICAL
        mLayout.setPadding(16)
        mLayout.addView(tvName)
        mLayout.addView(etName)
        mLayout.addView(tvComment)
        mLayout.addView(etComment)
        builder.setView(mLayout)

        builder.setTitle("방명록 추가")
        builder.setPositiveButton("추가") { _, _ ->
            val data = hashMapOf(
                "name" to etName.text.toString(),
                "comment" to etComment.text.toString()
            )
            db.collection("articles")
                .add(data)
                .addOnSuccessListener {
                    Toast.makeText(this, "데이터가 추가되었습니다", Toast.LENGTH_SHORT).show()
                    commentUpdate()
                }
                .addOnFailureListener { exception ->
                    Log.w("CommentActivity", "Error for: $exception")
                }
        }
        builder.setNegativeButton("취소") { _, _ ->

        }
        builder.show()
    }
}

 

 

 

Firestore Database 에 추가 확인

 

 

 

참고

 

Cloud Firestore로 데이터 가져오기  |  Firebase

의견 보내기 Cloud Firestore로 데이터 가져오기 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 세 가지 방법으로 Cloud Firestore에 저장된 데이터를 검색할 수 있

firebase.google.com

 

 

[Android/Firebase] Firestore 읽기, 쓰기

이번 글에서는 Firestore에 저장된 데이터를 읽어 리사이클러 뷰에 추가하는 것과, 앱에서 Firestore 데이터베이스에 데이터를 추가하는 법을 알아본다. Firestore에 문서 추가 먼저 Firestore에 문서를 추

mechacat.tistory.com