Kotlin Firebase RecyclerView 的问题

Problem with Kotlin Firebase RecyclerView

我试图在一个片段中创建一个用户回收视图,但我无法让它工作。

思路是从数据库中获取用户(实际登录的用户除外)并将用户数据添加到列表中。问题是这个列表甚至都没有出现。

我对 Kotlin 了解不多,我最近才开始使用它,但我为此苦苦挣扎。也不知道问题出在哪里

如果您需要 XML,请提出要求

我的片段:

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.*


@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class UsersFragment:Fragment(R.layout.fragment_users) {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapterUsers: AdapterUsers
    private lateinit var userList: MutableList<ModelUsers>

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        super.onCreate(savedInstanceState)
        (activity as AppCompatActivity).supportActionBar?.title = "Users"
    val view: View = inflater.inflate(R.layout.fragment_users, container, false)

    userList = ArrayList()

    getAllUsers()

    adapterUsers = AdapterUsers(context!!, userList)

    recyclerView = view.findViewById(R.id.users_recyclerView)
    recyclerView.setHasFixedSize(true)
    recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    recyclerView.adapter = adapterUsers

    return view
}

private fun getAllUsers() {
    val fUser: FirebaseUser = FirebaseAuth.getInstance().currentUser
    val ref: DatabaseReference = FirebaseDatabase.getInstance().getReference("Users")

    ref.addValueEventListener(object: ValueEventListener{
        override fun onDataChange(snapshot: DataSnapshot) {
            Log.d("FUNCTION", "ENTER")
            userList.clear()
            for(ds: DataSnapshot in snapshot.children){
                val modelUsers: ModelUsers? = ds.getValue(ModelUsers::class.java)

                if(!modelUsers?.uid.equals(fUser.uid)){
                    userList.add(modelUsers!!)
                    Toast.makeText(activity, "IN", Toast.LENGTH_SHORT).show()
                }
            }
        }

        override fun onCancelled(error: DatabaseError) {
            TODO("Not yet implemented")
        }

    })
}

companion object {
    fun newInstance(): ProfileFragment {
        return ProfileFragment()
    }}}

我的自定义适配器:

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import java.lang.Exception

open class AdapterUsers(private var context:Context, private var userList: MutableList<ModelUsers> = mutableListOf<ModelUsers>()): RecyclerView.Adapter<AdapterUsers.UserViewHolder>() {


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

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        val userImage = userList[position].image
        val userName = userList[position].name
        val userEmail = userList[position].email

        holder.mNameTv.text = userName
        holder.mEmailTv.text = userEmail
        try {
            Picasso.get().load(userImage).placeholder(R.drawable.ic_default_image_color).into(holder.mAvatarIv)
        }
        catch (e: Exception){

        }

        holder.itemView.setOnClickListener{
            Toast.makeText(context, userEmail, Toast.LENGTH_SHORT).show()
        }
    }

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

    inner class UserViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        val mAvatarIv: ImageView = itemView.findViewById(R.id.avatarIv)
        val mNameTv: TextView = itemView.findViewById(R.id.nameTv)
        val mEmailTv: TextView = itemView.findViewById(R.id.emailTv)
    }
}

用户模型:

data class ModelUsers(
var name: String? = null,
var email: String? = null,
var search: String? = null,
var phone: String? = null,
var image: String? = null,
var cover: String? = null,
var uid: String? = null)

问题是,当您使用适配器时,列表是空的,然后可能 0.2 秒后,您从数据库中获取用户并填充列表,但适配器不知道列表已更改。填充列表后,您可以在适配器上调用 notifyDataSetChanged() 以让它知道列表已更改。

您应该在数据更改后刷新您的回收器视图适配器,尝试像这样更改您的代码:

class UsersFragment:Fragment(R.layout.fragment_users) {

    private lateinit var recyclerView: RecyclerView
    
    private var userList = mutableListOf<ModelUsers>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        super.onCreate(savedInstanceState)
        (activity as AppCompatActivity).supportActionBar?.title = "Users"
        val view: View = inflater.inflate(R.layout.fragment_users, container, false)

        recyclerView = view.findViewById<RecyclerView>(R.id.users_recyclerView).apply {
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(requireContext())
            adapter = AdapterUsers(requireContext(), mutableListOf())
        }

        getAllUsers()

        return view
    }

    private fun getAllUsers() {
        val fUser: FirebaseUser = FirebaseAuth.getInstance().currentUser
        val ref: DatabaseReference = FirebaseDatabase.getInstance().getReference("Users")

        ref.addValueEventListener(object: ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                Log.d("FUNCTION", "ENTER")
                userList.clear()

                for(ds: DataSnapshot in snapshot.children) {
                    val modelUsers: ModelUsers? = ds.getValue(ModelUsers::class.java)

                    if(!modelUsers?.uid.equals(fUser.uid)){
                        userList.add(modelUsers!!)
                        Toast.makeText(activity, "IN", Toast.LENGTH_SHORT).show()
                    }

                    recyclerView.adapter = AdapterUsers(requireContext(), userList)
                }
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }

        })
    }

    companion object {
        fun newInstance(): ProfileFragment {
            return ProfileFragment()
        }
    }
}