我在应用程序中添加了分页功能,但是数据无法加载更多。当我设置20个数据的限制时,我添加23个数据并加载更多数据,则20个数据不可见,而3个数据可见。谁能帮我解决此错误?
前20个数据集的屏幕截图:
我滚动时的屏幕截图:
代码:
@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);
}
}
}
});
}
答案 0 :(得分:1)
您有这种行为,因为执行第二次查询以获取这三个新项目时,您将使用以下代码行清除documentsList
:
documentsList.clear();
要解决此问题,只需将其从第二个查询中删除,因为您需要添加更多数据,并且要添加到列表中而不要删除初始数据。我已经回答了类似的问题 here 。