Firestore Paging Adapter- How to know if query returns 0 results

后端 未结 2 1350
无人及你
无人及你 2020-12-07 05:51

I\'m using firestore paging adapter to populate my RecyclerView with data from Firestore, if collection in Firestore is empty I would like to show a TextV

相关标签:
2条回答
  • 2020-12-07 06:21

    I solved this problem by simple code. Just override onLoadingStateChangedListner method inside your FirestorePagingAdapter and then use getItemCount. I implemented it as follow -

    @Override
    protected void onLoadingStateChanged(@NonNull LoadingState state) {
        switch (state){
            case LOADED:
            case FINISHED:
                progressBar.setVisibility(View.GONE);
                if(getItemCount() == 0) {
                    emptyIcon.setVisibility(View.VISIBLE);
                    recyclerview.setVisibility(View.GONE);
                }
                break;
        }
        super.onLoadingStateChanged(state);
    }
    
    0 讨论(0)
  • 2020-12-07 06:32

    To get the number of items that are returned by the query which is passed to the FirestorePagingOptions object, you need to use getItemCount() method that exist in your adapter class. Because the data from Cloud Firestore is loaded asynchronously, you cannot simply call getItemCount() directly in your adapter class, as it will always be zero. So in order to get the total number of items, you need to register an observer like in the following lines of code:

    mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        public void onItemRangeInserted(int positionStart, int itemCount) {
            int totalNumberOfItems = adapter.getItemCount();
            Log.d(TAG, String.valueOf(totalNumberOfItems));
            if(totalNumberOfItems == 0) {
                recyclerView.setVisibility(View.GONE);
                emptyInfoTextView.setVisibility(View.VISIBLE);
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题