How to check if Cloud Firestore collection exists?

2020-04-17 07:26发布

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) 

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

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

2条回答
ゆ 、 Hurt°
2楼-- · 2020-04-17 08:02

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

Here is an example from my code:

  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());
            }
        }
    });
查看更多
ゆ 、 Hurt°
3楼-- · 2020-04-17 08:05

exists() applies to DocumentSnapshot while you're dealing with QuerySnapshot

Call task.result for getting QuerySnapshot out of Task<QuerySnapshot>.

From that, call result.getDocuments() and iterate through each of the DocumentSnapshot calling exists() on them.

查看更多
登录 后发表回答