【问题标题】:Populating RecyclerView with two sets of data from Firebase使用 Firebase 中的两组数据填充 RecyclerView
【发布时间】:2018-05-29 16:09:25
【问题描述】:

我已经设置了 Firebase...

{
  "items" : {
    "-LDJak_gdBhZQ0NSB-7B" : { //item
      "name" : "Test123",
       ...
    },
    ...
  },
  "likes" : {
    "YoTjkR2ORlcr5hGedzQs5xOK2VE3" : { //user
      "-LDJiY0YSraa_RhxVWXL" : true //whether or not the item is liked
    },
    ...
  }
}

我正在用项目填充RecyclerView,但我需要知道当前用户是否喜欢每个项目。我知道我可以将每个喜欢某个项目的用户存储在项目本身中,但这似乎太多重复了。但即使这样做,我也必须检查一个用户列表,该列表为该特定用户喜欢某个项目,对于添加的每个项目。我应该忍受所有这些重复还是有一个简单的方法来处理这个?这是我使用FirebaseRecyclerAdapter的代码:

private fun setUpFirebaseAdapter() {
        val ref = FirebaseDatabase.getInstance().reference

        val itemQuery = ref
                .child("items")
                .limitToLast(20)

        val itemOptions = FirebaseRecyclerOptions.Builder<Item>()
                .setQuery(itemQuery, Item::class.java)
                .build()


        firebaseAdapter = object : FirebaseRecyclerAdapter<Item, FirebaseViewHolder>(itemOptions) {

            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FirebaseViewHolder {
                val view = LayoutInflater.from(parent.context)
                        .inflate(R.layout.item_row, parent, false)

                return FirebaseViewHolder(view)
            }

            override fun onBindViewHolder(holder: FirebaseViewHolder, position: Int, model: Item) {
                holder.bindItems(model)
                //...
            }
        }
    }

我知道有索引支持,但我认为这只允许我只返回喜欢的项目。

【问题讨论】:

    标签: android firebase firebase-realtime-database kotlin


    【解决方案1】:

    但这似乎太多重复了。

    是的。

    我应该忍受所有这些重复,还是有一种简单的方法可以解决这个问题?

    是的,你应该这样做!

    在您的这种情况下,您应该使用在 Firebase 中命名为 denormalization 的这种技术,为此我建议您查看本教程 Denormalization is normal with the Firebase Database,以便更好地理解。

    因此,您所做的并没有错,除了 Firebase 的常见做法。

    【讨论】:

    • 有趣。谢谢你。不过,好奇的是,为每个项目的喜欢加载所有键只是为了在每个项目上搜索一个值,这不是非常低效吗?也许这只是使用 nosql 的缺点之一
    • 是的,为什么要复制数据以便只能查询特定数据是低效的。
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多