如何检查Cloud Firestore集合是否存在? (querysnapshot) [英] How to check if Cloud Firestore collection exists? ( querysnapshot)

查看:69
本文介绍了如何检查Cloud Firestore集合是否存在? (querysnapshot)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在检查我的收藏集是否存在于Firestore数据库中时遇到了麻烦。
当我使用Firebase Realtime数据库时,我可以使用:

I'm having trouble with checking if my collections exists in Firestore database. When I was working with Firebase Realtime database i could have used:

if(databaseSnapshot.exists) 

现在有了Firestore,我也想这样做。
我已经尝试过

Now with Firestore I wanna do the same. I have already tried

  if (documentSnapshots.size() < 0) 

但它不起作用。
这是当前代码:

but it doesn't work. Here is the current code:

public void pullShopItemsFromDatabase() {
    mShopItemsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (DocumentSnapshot document : task.getResult()) {
                    ShopItem shopItem = document.toObject(ShopItem.class);
                    shopItems.add(new ShopItem(shopItem.getImageUrl(), shopItem.getTitle(), shopItem.getSummary(), shopItem.getPowerLinkID(), shopItem.getlinkToShopItem(),shopItem.getLinkToFastPurchase(), shopItem.getKey(), shopItem.getPrice(),shopItem.getVideoID()));
                }
                if (shopItems != null) {
                    Collections.sort(shopItems);
                    initShopItemsRecyclerView();
                }
            } else {
                Log.w(TAG, "Error getting documents.", task.getException());
                setNothingToShow();
            }
        }
    });
}

函数:setNothingToShow();
实际上是我要执行的操作,如果我的收藏集为空/不存在。
请指教!
谢谢,
D。

the function: setNothingToShow(); Is actually what I wanna execute if my collection is empty / doesn't exists. Please advise! Thanks, D.

推荐答案

使用 DocumentSnapshot.size()> ; 0 检查集合是否存在。

Use DocumentSnapshot.size() > 0 to check if the collection exists or not.

以下是我的代码示例:

  db.collection("rooms").whereEqualTo("pairId",finalpairs)
         .get()
         .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                if(task.getResult().size() > 0) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d(FTAG, "Room already exists, start the chat");

                    }
                } else {
                    Log.d(FTAG, "room doesn't exist create a new room");

                }
            } else {
                Log.d(FTAG, "Error getting documents: ", task.getException());
            }
        }
    });

这篇关于如何检查Cloud Firestore集合是否存在? (querysnapshot)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆