I read Firestore documentation and all articles on internet(stackoverflow) about Firestore pagination but no luck. I tried to implement the exact code in docs, but nothing h
You can also use FirestorePagingAdapter
provided by Firebase-UI-Firestore
You need to install this dependency
implementation 'com.firebaseui:firebase-ui-firestore:latest_version_here'
Step 1: Create a global Firestore paging adapter variable and pass the Model class and ViewHolder, and also the Model variable.
private FirestorePagingAdapter adapter;
private Model model;
Step 2: Create a firebase query
Query query = db.collection("cities")
.orderBy("population");
Step 3: Let's build the pagedlist config. Here you will pass how much data to be queried in each page;
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.setPageSize(15)
.build();
Step 4: After setting the config, let's now build the Firestore paging options where you will pass the query
and config
.
FirestorePagingOptions options = new FirestorePagingOptions.Builder()
.setLifecycleOwner(this)
.setQuery(query, config, snapshot -> {
model = snapshot.toObject(Model.class);
return model;
})
.build();
Step: 5 Now let's pass the data to the Recylerview
adapter = new FirestorePagingAdapter(options) {
@Override
protected void onBindViewHolder(@NonNull ModelViewHolder holder, int position, @NonNull Model model) {
holder.bindTO(model);
}
@NonNull
@Override
public ModelViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_model, parent, false);
return new ModelViewHolder(view);
}
@Override
protected void onError(@NonNull Exception e) {
super.onError(e);
//logic here
}
@Override
protected void onLoadingStateChanged(@NonNull LoadingState state) {
switch (state) {
case LOADING_INITIAL:
break;
case LOADING_MORE:
break;
case LOADED:
notifyDataSetChanged();
break;
case ERROR:
Toast.makeText(requireActivity(), "Error", Toast.LENGTH_SHORT).show();
//logic here
break;
case FINISHED:
//logic here
break;
}
}
};
productRecycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Happy Coding!