正如official documentation中提到的,解决这个问题的关键是使用startAfter()方法。因此,您可以通过将查询游标与limit() 方法组合来对查询进行分页。您将能够使用批次中的最后一个文档作为下一个批次的光标的开始。
要解决这个分页问题,请参阅我的回答 post,我在其中逐步解释了如何从 Cloud Firestore 数据库中以较小的块加载数据并显示它在一个ListView 按钮点击。
解决方案:
要从您的 Firestore 数据库中获取数据并将其以较小的块显示在 RecyclerView 中,请按照以下步骤操作。
让我们以上面我使用过产品的例子为例。你可以使用产品、城市或任何你想要的东西。原理是一样的。假设您想在用户滚动时加载更多产品,我将使用RecyclerView.OnScrollListener。
让我们首先定义RecyclerView,将布局管理器设置为LinearLayoutManager,然后创建一个列表。我们还使用空列表实例化适配器并将适配器设置为我们的RecyclerView:
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<ProductModel> list = new ArrayList<>();
ProductAdapter productAdapter = new ProductAdapter(list);
recyclerView.setAdapter(productAdapter);
假设我们有一个如下所示的数据库结构:
Firestore-root
|
--- products (collection)
|
--- productId (document)
|
--- productName: "Product Name"
还有一个看起来像这样的模型类:
public class ProductModel {
private String productName;
public ProductModel() {}
public ProductModel(String productName) {this.productName = productName;}
public String getProductName() {return productName;}
}
适配器类应该是这样的:
private class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder> {
private List<ProductModel> list;
ProductAdapter(List<ProductModel> list) {
this.list = list;
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ProductViewHolder productViewHolder, int position) {
String productName = list.get(position).getProductName();
productViewHolder.setProductName(productName);
}
@Override
public int getItemCount() {
return list.size();
}
}
item_product 布局仅包含一个视图,TextView。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_view"
android:textSize="25sp"/>
这就是持有者类的样子:
private class ProductViewHolder extends RecyclerView.ViewHolder {
private View view;
ProductViewHolder(View itemView) {
super(itemView);
view = itemView;
}
void setProductName(String productName) {
TextView textView = view.findViewById(R.id.text_view);
textView.setText(productName);
}
}
现在,让我们将限制定义为全局变量并将其设置为15。
private int limit = 15;
现在让我们使用这个限制来定义查询:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference productsRef = rootRef.collection("products");
Query query = productsRef.orderBy("productName", Query.Direction.ASCENDING).limit(limit);
以下是在您的情况下也能发挥作用的代码:
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
ProductModel productModel = document.toObject(ProductModel.class);
list.add(productModel);
}
productAdapter.notifyDataSetChanged();
lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1);
RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = ((LinearLayoutManager) recyclerView.getLayoutManager());
int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
int visibleItemCount = linearLayoutManager.getChildCount();
int totalItemCount = linearLayoutManager.getItemCount();
if (isScrolling && (firstVisibleItemPosition + visibleItemCount == totalItemCount) && !isLastItemReached) {
isScrolling = false;
Query nextQuery = productsRef.orderBy("productName", Query.Direction.ASCENDING).startAfter(lastVisible).limit(limit);
nextQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> t) {
if (t.isSuccessful()) {
for (DocumentSnapshot d : t.getResult()) {
ProductModel productModel = d.toObject(ProductModel.class);
list.add(productModel);
}
productAdapter.notifyDataSetChanged();
lastVisible = t.getResult().getDocuments().get(t.getResult().size() - 1);
if (t.getResult().size() < limit) {
isLastItemReached = true;
}
}
}
});
}
}
};
recyclerView.addOnScrollListener(onScrollListener);
}
}
});
其中lastVisible 是一个DocumentSnapshot 对象,它表示查询中的最后一个可见项。在这种情况下,每 15 次,它被声明为一个全局变量:
private DocumentSnapshot lastVisible;
而isScrolling和isLastItemReached也是全局变量,声明为:
private boolean isScrolling = false;
private boolean isLastItemReached = false;
如果您想实时获取数据,那么您需要使用addSnapshotListener(),而不是使用get() 调用,如有关listening to multiple documents in a collection 的官方文档中所述。更多信息您可以找到以下文章: