尽管在 kotlin Xml Android 中成功获取和适配器设置,Firebase RecyclerView 未在片段中显示检索到的数据

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

我无法在 Android 应用程序的 RecyclerView 中显示从 Firebase 实时数据库检索的数据。 尽管成功获取数据(通过日志记录确认),但在显示片段时 RecyclerView 仍为空。 我实现了一个带有多个视图持有者(TextViewHolder、ImageViewHolder、VideoViewHolder、ImageVideoViewHolder)的 RecyclerView 适配器(postadapter)来处理不同类型的帖子内容(文本、图像、视频)。 适配器调试日志:尽管初始化了适配器并从适配器内部进行了日志记录(Log.d 语句),但 Logcat 中没有出现任何日志,这表明 RecyclerView 或适配器的更新或呈现方式存在潜在问题。 UI 渲染:尽管数据可用且从 Firebase 正确获取,但 RecyclerView 在视觉上仍然是空的。

我已经实现了一个带有多个视图持有者(TextViewHolder,ImageViewHolder,VideoViewHolder,ImageVideoViewHolder)的RecyclerView适配器(communitypostadapter)来处理不同类型的帖子内容(文本,图像,视频),并且我已经在Fragment中实现了一个RecyclerView,它实际上是为了显示片段内的选项卡和 Toast,以便初始化片段,但从 firebase 检索值并将其显示在 recylerview 中将无法工作。从日志中我了解到检索值是有效的。我不明白出了什么问题。我将提供相关代码和数据库结构。 后片段:

class postscommunityfragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_postscommunityfragment, container, false)

        recyclerView = view.findViewById(R.id.recycler_view_posts)

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = LinearLayoutManager(context)
        postList = mutableListOf()

        val name = arguments?.getString("name")
        Toast.makeText(context, name, Toast.LENGTH_LONG).show()

        val user = FirebaseAuth.getInstance().currentUser
        val userId = user?.uid

        databaseRef = FirebaseDatabase.getInstance().getReference("Posts").child(name!!).child(userId!!)

        databaseRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                postList.clear()
                for (postSnapshot in snapshot.children) {
                    val post = postSnapshot.getValue(postdataclass::class.java)
                    post?.let { postList.add(it) }
                }
                // Initialize adapter and set it after fetching posts
                postAdapter = communitypostadapter(requireContext(), postList)
                recyclerView.adapter = postAdapter
                Log.d("postscommunityfragment", "Fetched ${postList.size} posts")
            }

            override fun onCancelled(error: DatabaseError) {
                Log.e("postscommunityfragment", "Database error: ${error.message}")
            }
        })
    }
}

接杆适配器:


class postadapter(private val context: Context, private val postList: List<postdataclass>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val TYPE_TEXT_ONLY = 0
        private const val TYPE_TEXT_IMAGE = 1
        private const val TYPE_TEXT_VIDEO = 2
        private const val TYPE_TEXT_IMAGE_VIDEO = 3
    }

    override fun getItemViewType(position: Int): Int {
        val post = postList[position]
        Log.d("communitypostadapter", "getItemViewType for position $position")
        return when {
            post.imguri != null && post.videouri != null -> TYPE_TEXT_IMAGE_VIDEO
            post.imguri != null -> TYPE_TEXT_IMAGE
            post.videouri != null -> TYPE_TEXT_VIDEO
            else -> TYPE_TEXT_ONLY
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        Log.d("communitypostadapter", "onCreateViewHolder for viewType $viewType")
        return when (viewType) {
            TYPE_TEXT_IMAGE -> ImageViewHolder(LayoutInflater.from(context).inflate(R.layout.communitypostimageitem, parent, false))
            TYPE_TEXT_VIDEO -> VideoViewHolder(LayoutInflater.from(context).inflate(R.layout.communitypostvideoitem, parent, false))
            TYPE_TEXT_IMAGE_VIDEO -> ImageVideoViewHolder(LayoutInflater.from(context).inflate(R.layout.communitypostvideoimageitem, parent, false))
            else -> TextViewHolder(LayoutInflater.from(context).inflate(R.layout.communityposttextitem, parent, false))
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val post = postList[position]
        Log.d("communitypostadapter", "onBindViewHolder for position $position")
        when (holder) {
            is TextViewHolder -> holder.bind(post)
            is ImageViewHolder -> holder.bind(post)
            is VideoViewHolder -> holder.bind(post)
            is ImageVideoViewHolder -> holder.bind(post)
        }
    }

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

    inner class TextViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val postText: TextView = itemView.findViewById(R.id.text_view_post)
        private val username: TextView = itemView.findViewById(R.id.text_view_username)

        fun bind(post: postdataclass) {
            Log.d("TextViewHolder", "bind post: ${post.post}")
            postText.text = post.post
            username.text = post.username
        }
    }

    inner class ImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val postText: TextView = itemView.findViewById(R.id.text_view_post)
        private val username: TextView = itemView.findViewById(R.id.text_view_username)
        private val postImage: ImageView = itemView.findViewById(R.id.image_view_post)

        fun bind(post: postdataclass) {
            Log.d("ImageViewHolder", "bind post: ${post.post}")
            postText.text = post.post
          
        }
    }

    //Also did created another two viewholder for videos and images
}

并且适配器内部的日志未显示,我创建了四个视图持有者,因为帖子可以仅包含帖子文本或包含许多图像的帖子文本或包含许多视频的帖子文本或包含视频和图像的帖子文本,这就是我创建四个视图持有者的原因我不知道片段或适配器内部的问题出在哪里?我还尝试将自定义值发送到适配器(如果它工作),但它不起作用。 我还将提供我的 Firebase 数据库结构:

{
  "CommunityPosts": {
    "name": {
      "ve7UmHpwqsuMeORHkKTffWWViZ8zd2": {
        "-O-_1nzOQs0hf7S5EOEw": {
          "currenttime": "currentimr",
          "post": "postdetails",
          "userimg": "uimgurl",
          "username": "username"
        },
        "-O-_2ES4itNTsmGccBye": {
          "currenttime": "currentime",
          "imguri": [
            "urls"
          ],
          "post": "post",
          "userimg": "uimgurl",
          "username": "username"
        },
        "-O-_2POg6ludb1x996FE": {
          "currenttime": "currenttime",
          "post": "post",
          "userimg": "userimg",
          "username": "username",
          "videouri": [
            "urls"
          ]
        },
        "-O-_2_URXwNDghuKoPrJ": {
          "currenttime": "currentime",
          "imguri": [
            "urls"
          ],
          "post": "post",
          "userimg": "",
          "username": "username",
          "videouri": [
            "urls"
          ]
        }
      }
    }
  }
}

我添加了结构,以便它可以帮助理解我的代码。我不知道问题出在哪里。

数据类:

data class postdataclass(
    val post: String? = null,
    val imguri: List<String>? = null,
    val videouri: List<String>? = null,
    val username: String? = null,
    val userimg: String? = null,
    val currenttime: String? = null
)

我们可以在 Fragment 中使用 RecylerView 吗?从日志中我可以理解它没有调用的适配器,所以它仍然让我感到困惑。

android android-fragments firebase-realtime-database android-recyclerview android-viewholder
1个回答
0
投票

据我所知,您的代码中的问题在于以下代码行:

databaseRef = FirebaseDatabase.getInstance().getReference("Posts").child(name!!).child(userId!!)

您在数据库中调用

.getReference("Posts")
not
.getReference("CommunityPosts")
的地方。传递给
getReference()
方法的节点名称应与数据库中的名称匹配。

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