Check for “no documents” state or empty data-set i

2020-03-31 06:32发布

问题:

I wrote a custom FirebaseRecylerAdapter, based on FirebaseUI documentation like this:

class FavoritesAdapter(lifecycleOwner: LifecycleOwner) : FirebaseRecyclerAdapter<Favorite, FavoritesAdapter.FavoritesHolder>(buildOptions(lifecycleOwner)) {

companion object {
    private fun buildQuery() = FirebaseDatabase.getInstance()
            .reference
            .child("favorites")
            .limitToLast(50)

    private fun buildOptions(lifecycleOwner: LifecycleOwner) = FirebaseRecyclerOptions.Builder<Favorite>()
            .setQuery(buildQuery(), Favorite::class.java)
            .setLifecycleOwner(lifecycleOwner)
            .build()
}

//...

This class overrides an onDataChanged() function:

override fun onDataChanged() {
    // Called each time there is a new data snapshot. You may want to use this method
    // to hide a loading spinner or check for the "no documents" state and update your UI.
    // ...

}

Now, how do I actually check for that "no documents" state in order to update my UI? I can find no way to check for an empty data-set. I am looking for something like getItemCount().

回答1:

The adapter does have an itemCount property and you can also use snapshots to get a live list of your model objects. Example:

override fun onDataChanged() {
    if (itemCount == 0) {
        // Do stuff
    }
}