如何使用Android对Firestore进行分页?

我阅读了Firestore文档和互联网上所有关于Firestore分页的文章(stackoverflow),但没有运气。我试图在文档中实现确切的代码,但没有任何反应。我有一个包含项目(超过1250或更多)的基本数据库,我想逐步获得它们。通过滚动以加载 15 个项目(到数据库中的最后一个项目)。

如果使用文档代码:

// Construct query for first 25 cities, ordered by population
Query first = db.collection("cities")
    .orderBy("population")
    .limit(25);

first.get()
    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot documentSnapshots) {
        // ...

        // Get the last visible document
        DocumentSnapshot lastVisible = documentSnapshots.getDocuments()
            .get(documentSnapshots.size() -1);

        // Construct a new query starting at this document,
        // get the next 25 cities.
        Query next = db.collection("cities")
            .orderBy("population")
            .startAfter(lastVisible)
            .limit(25);

        // Use the query for pagination
        // ...
    }
});

怎么办?文档没有太多细节。

PS:当用户滚动时,我需要使用回收器视图(不是列表视图)。谢谢


答案 1

正如官方文档中提到的,解决此问题的关键是使用startAfter()方法。因此,您可以通过将查询游标与该方法组合来对查询进行分页。您将能够使用批处理中的最后一个文档作为下一个批处理的游标的开始。limit()

为了解决这个分页问题,请参阅我在这篇文章中的答案,其中我逐步解释了如何从Cloud Firestore数据库加载更小的块中的数据,并在单击按钮时显示它。ListView

溶液:

要从 Firestore 数据库中获取数据并将其以较小的块形式显示在 中,请按照以下步骤操作。RecyclerView

让我们以上面的例子为例,其中我使用了产品。您可以使用产品,城市或任何您想要的东西。原则是一样的。假设您希望在用户滚动时加载更多产品,我将使用 .RecyclerView.OnScrollListener

让我们首先定义 ,将布局管理器设置为 并创建一个列表。我们还使用空列表实例化适配器,并将适配器设置为我们的:RecyclerViewLinearLayoutManagerRecyclerView

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_productTextView

<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);
        }
    }
});

其中是一个对象,它表示查询中的最后一个可见项。在本例中,每 15 个,它被声明为一个全局变量:lastVisibleDocumentSnapshot

private DocumentSnapshot lastVisible;

和 也是全局变量,声明为:isScrollingisLastItemReached

private boolean isScrolling = false;
private boolean isLastItemReached = false;

如果要实时获取数据,则需要使用官方文档中有关侦听集合中多个文档的说明,而不是使用调用。有关详细信息,您可以找到以下文章:get()addSnapshotListener()


答案 2

FirebaseUI-Android最近还推出了Firestore Paginator。

我已经在我的代码中使用了它,它工作得很好 - 请记住,它使用.get()而不是.addSnapshotListener()来运行,所以回收器不是实时的。

请参阅此处的文档:

https://github.com/firebase/FirebaseUI-Android/tree/master/firestore#using-the-firestorepagingadapter


推荐