3

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
WhiteNinja
  • 53
  • 1
  • 1
  • 8
  • `if (documentSnapshots.size() < 0)` will never be true. It should be `if (documentSnapshots.size() == 0)` or `if (documentSnapshots.size() > 0)` (depending on where you put it). – Frank van Puffelen Dec 31 '17 at 15:16
  • @FrankvanPuffelen OK! I don't know what happened but now it worked. I have tried before with <= it didnt work, now it does. Thank's a lot! But this case works while I'm working with onSuccess. I was working before with onComplete because I want to make a "for" loop. like I did in the original post, can It work with onSuccess too? – WhiteNinja Dec 31 '17 at 16:19
  • `onSuccess` fires when the task has completed and succeeded. A task that completes without loading any data, because it didn't need to load any data, also succeeded. So `onSuccess` will work there too. – Frank van Puffelen Dec 31 '17 at 22:26
  • @FrankvanPuffelen thanks again. I have watched the introduction video of cloud Firestore, he uses there the "this" listener on "OnSuccess" before "new" keyword. all of that On onStart to achieve refreshing the content automatically. While using this method on fragments I have noticed it can break the fragment transaction, I assume because it clashes with several onStart methods (cause every fragment implements it) Any suggestions to avoid it? – WhiteNinja Jan 01 '18 at 12:25
  • I am not too familiar with transaction lifecycle, so can't be of help there. – Frank van Puffelen Jan 01 '18 at 16:11

2 Answers2

6

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());
            }
        }
    });
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Raj
  • 946
  • 12
  • 16
3

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.

rgoncalv
  • 5,825
  • 6
  • 34
  • 61