无法在 Android Strudio 的视图模型中运行数据绑定

问题描述 投票:0回答:1

我正在尝试克隆 Instagram。使用 mvvm 和数据绑定。我的主页运行良好,但当我进入详细信息页面时,我看不到我的帖子的图片、用户的电子邮件、用户的照片。我认为数据绑定正在获取我的视图模型的空值。所以我决定使用 init 函数。我发送 postId 作为参数。但它仍然是一样的。我看不到我的照片。我看到默认的 android 矢量。这些是我的代码。感谢您的帮助。 ->


    package com.example.firebasedeneme.views
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.View
    import android.widget.Toast
    import androidx.databinding.DataBindingUtil
    import androidx.lifecycle.Observer
    import androidx.lifecycle.ViewModelProvider
    import androidx.lifecycle.get
    import androidx.recyclerview.widget.LinearLayoutManager
    import com.example.firebasedeneme.mvvm.DetailedPostViewmodel
    import com.example.firebasedeneme.R
    import com.example.firebasedeneme.adapter.CommentsAdapter
    import com.example.firebasedeneme.databinding.ActivityDetailedPostBinding
    import com.example.firebasedeneme.model.Comment
    import com.example.firebasedeneme.model.Post
    import com.example.firebasedeneme.mvvm.MyViewmodelFactory
    import com.google.firebase.auth.ktx.auth
    import com.google.firebase.ktx.Firebase
    
    
    class DetailedPostActivity : AppCompatActivity() {
    
        val auth = Firebase.auth
        private lateinit var binding: ActivityDetailedPostBinding
        private lateinit var viewmodel: DetailedPostViewmodel
        lateinit var post: Post
        private lateinit var adapter: CommentsAdapter
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = DataBindingUtil.setContentView(this, R.layout.activity_detailed_post)
            binding.homePageActivity = HomePageActivity()
    
    
            binding.commentRecyclerView.layoutManager = LinearLayoutManager(this@DetailedPostActivity)
            adapter = CommentsAdapter(arrayListOf())
            binding.commentRecyclerView.adapter = adapter
    
            post = intent.getSerializableExtra("post") as Post
    
            viewmodel = ViewModelProvider(this, MyViewmodelFactory(application, post.postId))
                .get(DetailedPostViewmodel::class.java)
            binding.detailedPostVM = viewmodel
            viewmodel.getData(post.postId)
    
            observeLiveData()
    
        }
    
        fun observeLiveData() {
            viewmodel.postLiveData.observe(this@DetailedPostActivity, Observer { post ->
                binding.detailedPost.visibility = View.VISIBLE
            })
    
            viewmodel.commentsLiveData.observe(this@DetailedPostActivity, Observer { commentList ->
                if (!commentList.isEmpty()) {
                    binding.commentRecyclerView.adapter = adapter
                    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
                }
            })
    
        }
    
    
        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()
            }
        }
    
    
        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)
                }else{
                    post.likedUsers.add(user.userId)
                    }
                adapter.notifyDataSetChanged()
            }
        }
    
    }

package com.example.firebasedeneme.mvvm

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.example.firebasedeneme.model.Comment
import com.example.firebasedeneme.model.Post
import com.google.firebase.Timestamp
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase

    class DetailedPostViewmodel(application: Application,val postId: String) : AndroidViewModel(application) {
        val auth = Firebase.auth
        val firestore = Firebase.firestore
        val postLiveData = MutableLiveData<Post>()
        val commentsLiveData = MutableLiveData<ArrayList<Comment>>()
        val nullLiveData = MutableLiveData<Boolean>()
        val commentList = ArrayList<Comment>()
    
        init {
            getData(postId)
        }
    
        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
                    }
                }
            }
    
    
            //**************YORUMLARI ALIYORUZ*************
            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()
                }
        }
    
        fun isAlreadyLiked() : Boolean{
            postLiveData.value?.let {
                return it.likedUsers.contains(auth.uid)
            }
        return false
        }
    }

    package com.example.firebasedeneme.mvvm
    
    import android.app.Application
    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.ViewModelProvider
    
    class MyViewmodelFactory(val application: Application,val postId: String) : ViewModelProvider.AndroidViewModelFactory(application){
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return DetailedPostViewmodel(application, postId) as T
        }
    
    }

    @BindingAdapter("android:downloadUrl")
    fun downloadImage(view: ImageView, url:String?) {
        view.downloadFromUrl(url, placeholderProgressBar(view.context))
    }

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android">
        <data>
    
            <variable
                name="detailedPostVM"
                type="com.example.firebasedeneme.mvvm.DetailedPostViewmodel" />
            <variable
                name="homePageActivity"
                type="com.example.firebasedeneme.views.HomePageActivity" />
    
        </data>
    
    <androidx.core.widget.NestedScrollView android:layout_height="wrap_content" android:layout_width="wrap_content">
        <LinearLayout android:id="@+id/detailedPost"
        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="@{homePageActivity.Companion.hashMapUsers.get(detailedPostVM.postLiveData.userId).userPhotoUrl}"/>
    
            <TextView
                android:id="@+id/postEmailText"
                android:layout_width="306dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:paddingRight="200dp"
                android:text="@{homePageActivity.Companion.hashMapUsers.get(detailedPostVM.postLiveData.userId).email}" />
        </LinearLayout>
    
        <TextView
            android:id="@+id/postOutlineText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:text="@{detailedPostVM.postLiveData.outline}"/>
    
    
        <ImageView
            android:id="@+id/postImageView"
            android:layout_width="249dp"
            android:layout_height="207dp"
            android:layout_gravity="left"
            android:layout_marginLeft="20dp"
            android:downloadUrl="@{detailedPostVM.postLiveData.imageUrl}"/>
    
        <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='@{String.valueOf(detailedPostVM.postLiveData.likedUsers.size)+" people liked"}'
                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:contentDescription="likeBtn"
                android:text='@{detailedPostVM.alreadyLiked ? "LIKED" : "LIKE"}'
                android:onClick="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"
                android:onClick="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"
                android:nestedScrollingEnabled="false"/>
    
            <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>
    </androidx.core.widget.NestedScrollView>
    </layout>


kotlin android-studio mvvm data-binding mobile-development
1个回答
0
投票

我刚刚添加了 binding.lifecyclyeOwner = this; 已经解决了。

© www.soinside.com 2019 - 2024. All rights reserved.