I have added pagination feature to my application, but data cannot load more. When i set a limit of 20 data, then i add 23 data and load more, 20 data is invisible and 3 data is visible. Can anyone help me to fix this error?
Screenshot of the first 20 data sets :
Screenshot of when i scroll :
Code :
@Override
protected void onStart() {
super.onStart();
collectionReference.limit(20).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if(!task.getResult().isEmpty()) {
documentsList.clear();
for (DocumentSnapshot documentSnapshot : task.getResult()) {
Documents documents = documentSnapshot.toObject(Documents.class);
documentsList.add(documents);
documentListAdapter.notifyDataSetChanged();
lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1);
}
RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleDocument = layoutManager.findFirstVisibleItemPosition();
int visibleDocumentCount = layoutManager.getChildCount();
int totalDocumentCount = layoutManager.getItemCount();
if (isScrolling && (firstVisibleDocument + visibleDocumentCount == totalDocumentCount) && !isLastItemReached) {
isScrolling = false;
collectionReferences.startAfter(lastVisible).limit(20).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
documentsList.clear();
for (DocumentSnapshot documentSnapshot : task.getResult()) {
Documents documents = documentSnapshot.toObject(Documents.class);
documentsList.add(documents);
documentListAdapter.notifyDataSetChanged();
lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1);
}
if (task.getResult().size() < 20) {
isLastItemReached = true;
}
}
}
});
}
}
};
recyclerViewDocument.addOnScrollListener(onScrollListener);
}
}
}
});
}