skip to Main Content

I m doing a instagram clone in android studio with kotlin. I am using firebase. The problem is I can’t see comment recycler view in post detail screen. I checked my commentList it is true. So my commentList.value is true. But I can’t see my recycler view. And also I set a nulltext if there is no comments but I can’t see it too.
These are my codes ->

class DetailedPostActivity : AppCompatActivity() {

    val auth = Firebase.auth
    private lateinit var binding: ActivityDetailedPostBinding
    private lateinit var viewmodel: DetailedPostViewmodel
    private lateinit var post: Post
    private lateinit var adapter: CommentsAdapter

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

        binding.commentRecyclerView.layoutManager = LinearLayoutManager(this@DetailedPostActivity)
        adapter = CommentsAdapter(arrayListOf())
        binding.commentRecyclerView.adapter = adapter

        post = intent.getSerializableExtra("post") as Post

        viewmodel = ViewModelProvider(this@DetailedPostActivity).get(DetailedPostViewmodel::class.java)
        viewmodel.getData(post.postId)
        observeLiveData()


        binding.sendBtn.setOnClickListener { send(it) }
        binding.likeBtn.setOnClickListener { like(it) }

    }

    fun observeLiveData() {
        viewmodel.postLiveData.observe(this@DetailedPostActivity, Observer { post ->
            try {
                binding.postEmailText.setText(HomePageActivity.hashMapUsers.get(post.userId)!!.email)
                Picasso.get().load(HomePageActivity.hashMapUsers.get(post.userId)!!.userPhotoUrl)
                    .into(binding.profilePhotoImageView)
            } catch (e: Exception) {
                println(e.printStackTrace())
            }
            binding.likeCountDetail.setText("${post.likedUsers.size} kişi beğendi")
            Picasso.get().load(post.imageUrl).into(binding.postImageView)
        })
        viewmodel.commentsLiveData.observe(this@DetailedPostActivity, Observer { commentList ->
            if (!commentList.isEmpty()) {
                adapter.yorumlariGuncelle(commentList)
                binding.commentRecyclerView.visibility = View.VISIBLE
                binding.nullCommentText.visibility = View.GONE
            } else {
                binding.commentRecyclerView.visibility = View.GONE
                binding.nullCommentText.visibility = View.VISIBLE
            }

        })

        viewmodel.nullLiveData.observe(this@DetailedPostActivity, Observer { bool ->
            if (bool) {
                binding.nullCommentText.visibility = View.VISIBLE
                binding.commentRecyclerView.visibility = View.GONE
            } else {
                binding.nullCommentText.visibility = View.GONE
            }
        })

    }


    private fun send(view: View) {
        val commentText = binding.commentText.text.toString()
        binding.commentText.text.clear()
        if (!commentText.isEmpty()) {
            val comment = Comment(auth.uid!!, post.postId, commentText)
            viewmodel.addComment(comment)
            adapter.notifyDataSetChanged()
        }else{
            Toast.makeText(this@DetailedPostActivity, "Yorum Yazınız!", Toast.LENGTH_LONG).show()
        }
    }


    private fun like(view: View){
        val userId = auth.uid
        val user = HomePageActivity.hashMapUsers.get(userId)
        user?.let {user->
            if(user.userId in post.likedUsers){
                post.likedUsers.remove(user.userId)
                binding.likeBtn.setText("LIKED")
            }else{
                post.likedUsers.add(user.userId)
                binding.likeBtn.setText("LIKE")
                }
            adapter.notifyDataSetChanged()
        }
    }
}
class DetailedPostViewmodel(application: Application) : AndroidViewModel(application) {
    val firestore = Firebase.firestore
    val postLiveData = MutableLiveData<Post>()
    val commentsLiveData = MutableLiveData<ArrayList<Comment>>()
    val nullLiveData = MutableLiveData<Boolean>()
    val commentList = ArrayList<Comment>()

    fun getData(postId:String) {
        nullLiveData.value = false

        //******İLGİLİ POSTU ALIYORUZ**********
        firestore.collection("Posts").document(postId).get().addOnSuccessListener {
            val hashmap = it.data
            hashmap?.let{hashmap->
                val userId = hashmap["userId"] as? String
                val imageUrl = hashmap["imageUrl"] as? String
                val outline = hashmap["outline"] as? String
                if(userId != null && imageUrl != null && outline != null){
                    val post = Post(userId,imageUrl,outline)
                    postLiveData.value = post
                }
            }
        }


        //**************TAKING COMMENTS*************
        firestore.collection("Posts").document(postId)
            .collection("Comments").orderBy("date",Query.Direction.DESCENDING)
            .addSnapshotListener { value, error ->
                if (error != null) {
                    Toast.makeText(getApplication(), error.localizedMessage, Toast.LENGTH_LONG)
                        .show()
                } else {
                    if (value != null && !value.isEmpty) {
                        val documents = value.documents
                        commentList.clear()
                        for (document in documents) {
                            val commentMap = document.get("comment") as? Map<String, Any>
                            commentMap?.let { map ->
                                val userId = map["userId"] as? String
                                val commentText = map["commentText"] as? String
                                if (userId != null && commentText != null) {
                                    commentList.add(Comment(userId, postId, commentText))
                                }
                            }
                        }
                        println(commentList)
                        commentsLiveData.value = commentList
                    } else {
                        nullLiveData.value = true
                    }
                }
            }
    }

    fun addComment(comment:Comment){
        firestore.collection("Posts").document(comment.postId)
            .collection("Comments")
            .add(hashMapOf("comment" to comment,"date" to Timestamp.now()))
            .addOnSuccessListener {
                Toast.makeText(getApplication(),"YORUMUNUZ PAYLAŞILDI!",Toast.LENGTH_SHORT).show()
                getData(comment.postId)
            }.addOnFailureListener {
                Toast.makeText(getApplication(),"YORUM YAPILAMADI!",Toast.LENGTH_LONG).show()
            }
    }
}package com.example.firebasedeneme.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.firebasedeneme.R
import com.example.firebasedeneme.databinding.RecyclerCommentRowBinding
import com.example.firebasedeneme.model.Comment
import com.example.firebasedeneme.views.HomePageActivity

class CommentsAdapter(val commentList:ArrayList<Comment>) : RecyclerView.Adapter<CommentsAdapter.CommentVH>(){
    inner class CommentVH(val binding:RecyclerCommentRowBinding) : RecyclerView.ViewHolder(binding.root) {

    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentVH {
        val binding = DataBindingUtil.inflate<RecyclerCommentRowBinding>(LayoutInflater.from(parent.context),
            R.layout.recycler_comment_row,parent,false)
        return CommentVH(binding)
    }

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

    override fun onBindViewHolder(holder: CommentVH, position: Int) {
        /*holder.binding.postEmailText.text = HomePageActivity.hashMapUsers.get(commentList[position].userId)!!.email
        holder.binding.yorumTextView.text = commentList[position].commentText
        //Picasso.get().load(HomePageActivity.hashMapUsers.get(commentList[position].userId)!!.userPhotoUrl).into(holder.binding.profilePhotoImageView)
         */
        val comment = commentList[position]
        holder.binding.comment = comment

        val user = HomePageActivity.hashMapUsers.get(comment.userId)
        user?.let{
            holder.binding.user = user
        }
    }

    fun yorumlariGuncelle(newCommentList:ArrayList<Comment>){
        commentList.clear()
        commentList.addAll(newCommentList)
        notifyDataSetChanged()
    }
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="user"
            type="com.example.firebasedeneme.model.User" />

        <variable
            name="comment"
            type="com.example.firebasedeneme.model.Comment" />
    </data>

    <LinearLayout
    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/profilePhotoImageView"
        android:layout_width="99dp"
        android:layout_height="72dp"
        android:downloadUrl="@{user.userPhotoUrl}"/>

    <TextView
        android:id="@+id/postEmailText"
        android:layout_width="306dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingRight="200dp"
        android:text="@{user.email}" />

    </LinearLayout>

    <TextView
        android:id="@+id/yorumTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:text="@{comment.commentText}"/>

</LinearLayout></layout><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
    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/profilePhotoImageView"
            android:layout_width="99dp"
            android:layout_height="72dp"
            android:src="@drawable/baseline_person_24"/>

        <TextView
            android:id="@+id/postEmailText"
            android:layout_width="306dp"
            android:layout_height="match_parent"
            android:gravity="center"
            android:paddingRight="200dp"
            android:text="NICKNAME" />
    </LinearLayout>

    <TextView
        android:id="@+id/postOutlineText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"/>


    <ImageView
        android:id="@+id/postImageView"
        android:layout_width="249dp"
        android:layout_height="207dp"
        android:layout_gravity="left"
        android:layout_marginLeft="20dp"/>

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

        <TextView
            android:id="@+id/likeCountDetail"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#2E53BD"
            android:textSize="12sp"
            android:gravity="left"
            android:text="22 KİŞİ BEĞENDİ"
            android:paddingLeft="10dp"/>

    </LinearLayout>



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

        <Button
            android:id="@+id/likeBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LIKE"/>
        <EditText
            android:id="@+id/commentText"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:hint="Yorum Yap..."
            android:textSize="22sp"/>
        <Button
            android:id="@+id/sendBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"/>

    </LinearLayout>

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


        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/commentRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp" />

        <TextView
            android:id="@+id/nullCommentText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="NO ANY COMMENT!"
            android:textAlignment="center"
            android:textSize="32sp" />
    </LinearLayout>
</LinearLayout>

> </layout>

detail activity layout

2

Answers


  1. Please try adding the adapter i.e, "binding.commentRecyclerView.adapter = adapter" after observing data from Viewmodel.

    Please Make sure Here "arrayListOf()" is giving valid data i.e the data observed from observeLiveData() method

    Login or Signup to reply.
  2. Wrap you activity’s LinearLayout inside androidx.core.widget.NestedScrollView and in RecyclerView add android:nestedScrollingEnabled="false". Hopes it will work if you have data in your list.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search