• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    해결됨

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

22.09.19 13:32 작성 조회수 204

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)
    }


}

답변 1

답변을 작성해보세요.

0

안녕하세요 주성님

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

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

 

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

정주성님의 프로필

정주성

질문자

2022.09.20

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

https://github.com/wjdwntjd55/MySoloLife

404가 뜨고 있네요..!

혹시 private일까요?

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

정주성님의 프로필

정주성

질문자

2022.09.27

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

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

https://github.com/wjdwntjd55/MySoloLife

안녕하세요 주성님

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

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

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

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

정주성님의 프로필

정주성

질문자

2022.10.08

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