繁体   English   中英

如何检查Cloud Firestore集合是否存在? (querysnapshot)

[英]How to check if Cloud Firestore collection exists? ( querysnapshot)

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

if(databaseSnapshot.exists) 

现在,在Firestore中,我想做同样的事情。 我已经尝试过

  if (documentSnapshots.size() < 0) 

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

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。

在处理QuerySnapshotQuerySnapshot exists()适用于DocumentSnapshot

调用task.result以将QuerySnapshotTask<QuerySnapshot>

从这一点,调用result.getDocuments()并通过每个迭代的DocumentSnapshot呼叫exists()他们。

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

这是我的代码中的一个示例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM