首页 > 解决方案 > Android - 从 Firebase Storage 获取所有下载链接后无法更新 RecyclerView

问题描述

我想从 Firebase 存储中获取所有视频文件并将它们显示在 RecyclerView 中。我已经设法获取所有文件,但是一旦检索到所有文件,我就无法更新 RecyclerView。这是代码

 recyclerViewVideoList.setHasFixedSize(true)
 recyclerViewVideoList.layoutManager = LinearLayoutManager(this)
 recyclerViewVideoList.adapter = VideoListRecyclerViewAdapter(applicationContext,videoList, this)
 getVideos()

 private fun getVideos() {
    val listRef = firebaseStorage.reference.child("videos")
    listRef.listAll()
        .addOnSuccessListener { listResult ->
            listResult.items.forEach { item ->
                item.downloadUrl.addOnSuccessListener {
                    videoList.add(Video(item.name, it.toString(), "565656"))
                }
            }
           recyclerViewVideoList.adapter!!.notifyDataSetChanged()
        }
        .addOnFailureListener {
            Toast.makeText(applicationContext, "Something went wrong. Please try again", Toast.LENGTH_SHORT).show()
        }
}

这里有一个解决方案,但它多次调用 notifyDataSetChanged() 。我想避免这样做。

标签: androidfirebaseandroid-recyclerviewfirebase-storage

解决方案


更有效的解决方案是仅对列表项的最后一个元素调用notifyDataSetChanged()函数。通过这样做,您的 notifyDataSetChanged() 函数仅针对最后一个元素执行并更新所有回收站视图。

改变这个:

   .addOnSuccessListener { listResult ->
        listResult.items.forEach { item ->
            item.downloadUrl.addOnSuccessListener {
                videoList.add(Video(item.name, it.toString(), "565656"))
            }
        }
       recyclerViewVideoList.adapter!!.notifyDataSetChanged()
    }

//Declare one integer count variable var count = 0

     .addOnSuccessListener { listResult ->
        listResult.items.forEach { item ->
            item.downloadUrl.addOnSuccessListener {
                videoList.add(Video(item.name, it.toString(), "565656"))
                count++
                if(count == listResult.items.size)
                   recyclerViewVideoList.adapter!!.notifyDataSetChanged()  
            }
        }
    }

推荐阅读