查询数据库时如何在 FirebaseUI RecylerAdapter 中设置过滤器?
How can I set a filter in a FirebaseUI RecylerAdapter when querying the database?
我使用的 FirebaseDatabase 包含 "categories" 和相关的 "details",如下所示:
注意:"categories" 中的 categoryId 作为 "details" 的主键。
我的 DetailAdapter 使用此查询与 FirebaseUI 的 RecyclerAdapter 一起工作:
class DetailAdapter(lifecycleOwner: LifecycleOwner, private val categoryId: String) : FirebaseRecyclerAdapter<Detail, DetailAdapter.DetailHolder>(buildOptions(lifecycleOwner, categoryId)) {
companion object {
private fun buildQuery(categoryId: String) = FirebaseDatabase.getInstance()
.reference
.child("").child("details").child(categoryId)
.limitToLast(50)
private fun buildOptions(lifecycleOwner: LifecycleOwner, categoryId: String) = FirebaseRecyclerOptions.Builder<Detail>()
.setQuery(buildQuery(categoryId), Detail::class.java)
.setLifecycleOwner(lifecycleOwner)
.build()
}
...
这完美无缺。
现在我想写一个类似的适配器(即命名为 "FavoritesAdapter")以便只显示具有 "favorite: [set to] true" 的 "details"。我可以使用 buildQuery 来实现吗?
无法使用 buildQuery 来实现此目的。解决方案的关键是一种称为 非规范化 的策略,这是 "Duplicating Data" 的礼貌说法。你可能想看这个解释:Denormalization is normal with Firebase Database。
我使用的 FirebaseDatabase 包含 "categories" 和相关的 "details",如下所示:
注意:"categories" 中的 categoryId 作为 "details" 的主键。
我的 DetailAdapter 使用此查询与 FirebaseUI 的 RecyclerAdapter 一起工作:
class DetailAdapter(lifecycleOwner: LifecycleOwner, private val categoryId: String) : FirebaseRecyclerAdapter<Detail, DetailAdapter.DetailHolder>(buildOptions(lifecycleOwner, categoryId)) {
companion object {
private fun buildQuery(categoryId: String) = FirebaseDatabase.getInstance()
.reference
.child("").child("details").child(categoryId)
.limitToLast(50)
private fun buildOptions(lifecycleOwner: LifecycleOwner, categoryId: String) = FirebaseRecyclerOptions.Builder<Detail>()
.setQuery(buildQuery(categoryId), Detail::class.java)
.setLifecycleOwner(lifecycleOwner)
.build()
}
...
这完美无缺。
现在我想写一个类似的适配器(即命名为 "FavoritesAdapter")以便只显示具有 "favorite: [set to] true" 的 "details"。我可以使用 buildQuery 来实现吗?
无法使用 buildQuery 来实现此目的。解决方案的关键是一种称为 非规范化 的策略,这是 "Duplicating Data" 的礼貌说法。你可能想看这个解释:Denormalization is normal with Firebase Database。