Firestore Paging Adapter- How To Know If Query Returns 0 Results
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 TextView
to inform user about that, if it is not then I would like to populate EecyclerView
with data but I don't see a way to do this with Firestore paging adapter because I can't acces data from inside the fragment where I create adapter
Im my Fragment
inside onViewCreated
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(2)
.setPageSize(5)
.build()
val options = FirestorePagingOptions.Builder<Question>()
.setLifecycleOwner(viewLifecycleOwner)
.setQuery(FirestoreUtil.myFeedQuery, config, Question::class.java)
.build()
mAdapter = WallFeedRVAdapter(this, options)
WallFeedRVAdapter is RecyclerView
adapter where I populate MyViewHolder
with loaded data. How can I from this current fragment that hosts RecyclerView
know if myFeedQuery returned any results so I can update recyclerView visibility to GONE and emptyInfoTextView to VISIBLE.
Answer
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);
}
}
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM