inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[초급편] 안드로이드 커뮤니티 앱 만들기(Android Kotlin)

댓글 불러오기

댓글 여러개 작성시 댓글이 안보임

해결된 질문

331

봉구형

작성한 질문수 2

0

선생님 저 질문이있어서 이렇게 문의드립니다.

댓글 불러오기강의에서 댓글을 여러개 작성을 하게 되면 사진에 보이는 것처럼 댓글을 새로 작성해도 화면에 보이지 않고있습니다.

스크린샷 2022-09-19 오후 1.13.05.png

infinite/endless scroll(무한 스크롤)기능을 추가해야하는지 싶어서 이렇게 문의드립니다.

activity_board_inside.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                tools:context=".board.BoardInsideActivity">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="60dp">

                    <androidx.constraintlayout.widget.ConstraintLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <TextView
                            android:id="@+id/titleArea"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="50dp"
                            android:layout_marginRight="50dp"
                            android:gravity="center"
                            android:text="title"
                            android:textColor="@color/black"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <ImageView
                            android:id="@+id/boardSettingIcon"
                            android:layout_width="20dp"
                            android:layout_height="40dp"
                            android:layout_margin="10dp"
                            android:src="@drawable/main_menu"
                            android:visibility="invisible"
                            app:layout_constraintEnd_toEndOf="parent"
                            app:layout_constraintTop_toTopOf="parent" />

                    </androidx.constraintlayout.widget.ConstraintLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0.5dp"
                    android:background="@color/black">

                </LinearLayout>

                <TextView
                    android:id="@+id/timeArea"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:gravity="right"
                    android:text="time" />

                <TextView
                    android:id="@+id/textArea"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_margin="20dp"
                    android:background="@drawable/background_radius"
                    android:padding="10dp"
                    android:text="여기는 내용 영역"
                    android:textColor="@color/black" />


                <ImageView
                    android:id="@+id/getImageArea"
                    android:layout_width="match_parent"
                    android:layout_height="300dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp" />

                <ListView
                    android:id="@+id/commentLV"
                    android:layout_width="match_parent"
                    android:layout_height="600dp" />

            </LinearLayout>
        </ScrollView>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_alignParentBottom="true"
            android:background="@color/white"
            android:layout_height="60dp">

            <EditText
                android:id="@+id/commentArea"
                android:hint="댓글을 입력해주세요"
                android:layout_marginLeft="10dp"
                android:layout_width="320dp"
                android:layout_height="match_parent"
                android:background="@android:color/transparent"/>

            <ImageView
                android:id="@+id/commentBtn"
                android:src="@drawable/btnwrite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </LinearLayout>

    </RelativeLayout>
</layout>

BoardInsideActivity.kt

package com.example.mysolelife.board

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import com.bumptech.glide.Glide
import com.example.mysolelife.R
import com.example.mysolelife.comment.CommentLVAdapter
import com.example.mysolelife.comment.CommentModel
import com.example.mysolelife.databinding.ActivityBoardInsideBinding
import com.example.mysolelife.utils.FBAuth
import com.example.mysolelife.utils.FBRef
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import java.lang.Exception

class BoardInsideActivity : AppCompatActivity() {

    private  val TAG = BoardInsideActivity::class.java.simpleName

    private lateinit var binding : ActivityBoardInsideBinding

    private lateinit var key : String

    private val commentDataList = mutableListOf<CommentModel>()

    private lateinit var commentAdapter : CommentLVAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_board_inside)

        binding.boardSettingIcon.setOnClickListener {
            showDialog()
        }

        // 첫 번째 방법
       /* val title = intent.getStringExtra("title").toString()
        val content = intent.getStringExtra("content").toString()
        val time = intent.getStringExtra("time").toString()

        binding.titleArea.text = title
        binding.textArea.text = content
        binding.timeArea.text = time*/

        // 두 번째 방법
        key = intent.getStringExtra("key").toString()

        getBoardData(key)
        getImageData(key)

        binding.commentBtn.setOnClickListener {
            insertComment(key)
        }

        commentAdapter = CommentLVAdapter(commentDataList)
        binding.commentLV.adapter = commentAdapter

        getCommentData(key)

    }

    private fun getBoardData(key : String) {

        val postListener = object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {

                try {

                    val dataModel = dataSnapshot.getValue(BoardModel::class.java)
                    Log.d(TAG, dataModel!!.title)

                    binding.titleArea.text = dataModel!!.title
                    binding.textArea.text = dataModel!!.content
                    binding.timeArea.text = dataModel!!.time

                    val myUid = FBAuth.getUid()
                    val writerUid = dataModel.uid

                    if(myUid.equals(writerUid)) {
                        binding.boardSettingIcon.isVisible = true
                    } else {

                    }

                } catch (e : Exception) {

                   Log.d(TAG, "삭제완료")

                }


            }

            override fun onCancelled(databaseError: DatabaseError) {
                // Getting Post failed, log a message
                Log.w("ContentListActivity", "loadPost:onCancelled", databaseError.toException())
            }
        }
        FBRef.boardRef.child(key).addValueEventListener(postListener)

    }

    private fun getImageData(key : String) {

        // Reference to an image file in Cloud Storage
        val storageReference = Firebase.storage.reference.child(key + ".png")

        // ImageView in your Activity
        val imageViewFromFB = binding.getImageArea

       storageReference.downloadUrl.addOnCompleteListener(OnCompleteListener { task ->
           if (task.isSuccessful) {

               Glide.with(this)
                   .load(task.result)
                   .into(imageViewFromFB)

           } else {
               binding.getImageArea.isVisible = false      // 이미지 사진이 없을 때
           }

       })

    }

    private fun showDialog() {

        val mDialogView = LayoutInflater.from(this).inflate(R.layout.custom_dialog, null)
        val mBuilder = AlertDialog.Builder(this)
            .setView(mDialogView)
            .setTitle("게시글 수정/삭제")

        val alertDialog = mBuilder.show()
        alertDialog.findViewById<Button>(R.id.editBtn)?.setOnClickListener {
            Toast.makeText(this, "수정 버튼을 눌렀습니다", Toast.LENGTH_LONG).show()

            val intent = Intent(this, BoardEditActivity::class.java)
            intent.putExtra("key", key)
            startActivity(intent)
        }

        alertDialog.findViewById<Button>(R.id.removeBtn)?.setOnClickListener {

            FBRef.boardRef.child(key).removeValue()
            Toast.makeText(this, "삭제완료", Toast.LENGTH_LONG).show()
            finish()
        }

    }

    fun insertComment(key : String){
        // 파이어베이스 구조
        // comment
        //  - BoardKey
        //      - CommentKey
        //          - CommentData
        //          - CommentData
        //          - CommentData
        FBRef.commentRef
            .child(key)
            .push()
            .setValue(
                CommentModel(
                    binding.commentArea.text.toString(),
                    FBAuth.getTime()
                )
            )

        Toast.makeText(this, "댓글 입력 완료", Toast.LENGTH_SHORT).show()
        binding.commentArea.setText("")


    }

    fun getCommentData(key: String){

        val postListener = object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {

                commentDataList.clear()

                for (dataModel in dataSnapshot.children) {
                    val item = dataModel.getValue(CommentModel::class.java)
                    commentDataList.add(item!!)
                }
                commentAdapter.notifyDataSetChanged()

            }

            override fun onCancelled(databaseError: DatabaseError) {
                // Getting Post failed, log a message
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
            }
        }
        FBRef.commentRef.child(key).addValueEventListener(postListener)
    }


}

android firebase kotlin

답변 1

0

개복치개발자

안녕하세요 주성님

유사한 질문이 있는데 한번 참고해보시겠어요?

https://www.inflearn.com/questions/630015

 

혹시 잘 안되시면 전체 코드를 깃허브에 올려놓으시고 링크를 공유해주세요~

0

봉구형

깃허브에 코드 올렸습니다!!

https://github.com/wjdwntjd55/MySoloLife

0

개복치개발자

404가 뜨고 있네요..!

혹시 private일까요?

그리고, 에러 해결을 위해 어떤 것을 해보셨는지도 알려주시겠어요?

0

봉구형

위에 댓글을 보고 일단 에러는 해결을 했는데, 댓글이 쓰여진 스크롤이 내려가는게 너무 빨라서 처음하고 마지막 댓글만 보이고 중간에 쓰여진 댓글들이 안보이는데 스크롤 속도를 어떻게 줄여야 할까요??

깃허브 코드 다시 올렸습니다.

https://github.com/wjdwntjd55/MySoloLife

0

개복치개발자

안녕하세요 주성님

저 속도라는게 어떤 것인지.. 뭔가 사용자가 클릭을 했을 때 이벤트인지 아니면 자동으로 스크롤인지

이 부분에 관해서 가능하면 스크린샷 혹은 동영상으로 보여주실 수 있으실까요?

아래의 링크의 질문처럼 자세히 문의주시면 문제를 좀 더 파악하기 쉽습니다 :)

https://www.inflearn.com/questions/639892

0

봉구형

잘 작동하네요 제가 잘못 스크롤을 해서 그런가보네요. 답변 감사합니다!!

이미지가 기본이미지인지 확인

0

132

1

NavController error 발생

0

141

1

fragment 생성하고 메인에서 불러왔는데 안뜹니다.

0

141

2

67강 댓글

0

100

2

7강 데이터바인딩 에러

0

116

2

Firebase 스토리지 유료화 문제

1

297

2

게시글 이미지가 파이어베이스에 저장되지 않습니다.

0

181

2

AVD 갤러리에 이미지 저장 안되는 문제

0

240

2

이미지 받아오는 방법?

0

204

2

회원탈퇴 기능을 추가하려고 합니다.

0

188

2

상태바 질문 드립니다.

0

111

1

섹션2 인트로 페이지 꾸미기 질문 드립니다.

0

110

1

게시판 글을 길게 쓸경우

0

124

2

로그인 로그아웃

0

177

2

갤럭시 연결시 게시판에 업로드한 사진이 보이지 않아요.

0

206

2

웹뷰 AVD 실행안됨

0

191

1

자막켜기가 안되요 ㅜ.ㅜ

1

185

1

리사이클러뷰, 그리드레이아웃 오류

0

186

2

리사이클러뷰 오류 해결 방법이 궁금합니다.

0

194

1

firebase 스마트폰으로 연결이 안되는데 원인이 있을까요

0

259

2

안드로이드 스튜디오 게시글 이미지 업로드 유무

0

217

1

firebase 설정 오류

0

304

2

홈 화면 커뮤니티

0

178

1

게시판 글 읽기

0

240

2