【问题标题】:how to know if data exists in a firestore query snapshot?如何知道数据是否存在于 Firestore 查询快照中?
【发布时间】:2018-11-10 02:35:25
【问题描述】:

这是我想要获取数据并知道数据是否存在的代码。 问题是如果数据存在,它会运行{ if(task.isSuccessful() },但如果数据不存在,它什么也不做!

我怎么知道数据不存在?我添加了其他 { else } 语句,但它不起作用。

CollectionReference reference = firestore.collection("Carts").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
            .collection("Carts");
    reference.whereEqualTo("ordered",false).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    if(document.exists()){
                        Toast.makeText(ListProducts.this, "Exists", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        // This part is not running even if there is no data
                        Toast.makeText(ListProducts.this, "NOPE", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    });

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    您需要像这样直接在QueryDocumentSnapshot 对象上使用exists() 方法:

    CollectionReference reference = firestore.collection("Carts").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .collection("Carts");
        reference.whereEqualTo("ordered",false).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.exists()) {
                             Toast.makeText(ListProducts.this, document.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                } else{
                    //This Toast will be displayed only when you'll have an error while getting documents.
                    Toast.makeText(ListProducts.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    

    task.isSuccessful() 用于处理侦听器中的成功或失败,而在扩展DocumentSnapshot 类的QueryDocumentSnapshot 类的对象上调用exists() 方法会返回:

    如果文档存在于此快照中,则为 true。

    【讨论】:

    • 试过这个,只有在数据存在时才有效,如果数据不存在,它什么也不返回,即使我添加了 else 语句或( !document.exists() )它也不起作用!
    • 如果只在数据存在的情况下有效,说明你不是在寻找不存在的数据。所以 if 语句的第二部分没有被调用是正常的。但是,如果数据存在于查询快照中,这是唯一的方法。
    • 另请参阅我在更新后的答案中添加到第二个 Toast 的评论。
    • 我更新了问题(代码部分)我评论了即使没有数据也没有运行的部分!
    • 逻辑上该部分在没有数据时必须运行,但它没有运行!
    【解决方案2】:

    您需要验证文档列表是否为空

    FirebaseFirestore.getInstance().collection(collectionName).whereEqualTo(cle
                , valeur)
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        QuerySnapshot querySnapshot = task.getResult();
                            if (querySnapshot.isEmpty()) { // no documents found
                                // Type your code yere
                            } else {
                                for (QueryDocumentSnapshot document : querySnapshot){
    
                                }
                            }
                    } else {
                        Log.d(TAG, methodName + task.getException());
                    }
                });
    

    如果我执行

    for (int i = 2; i < 1; i ++) { }
    

    没关系,但我们永远不会进入这个循环。上面的代码也是这样

    【讨论】:

      【解决方案3】:

      通过isEmpty()或size()方法成功完成任务时检查文档是否存在

      if (task.isSuccessful()) {
          if(task.getResult().isEmpty()){
              //There is no such document do what ever you want!   
          }
          else {
              for (QueryDocumentSnapshot document : task.getResult()) {
                  if (document.exists()) {
                      Toast.makeText(ListProducts.this, document.toString(), Toast.LENGTH_SHORT).show();
                  }
              }
          }
      }
      

      if(task.getResult().size > 0){
          //Document exist
      }
      

      【讨论】:

        【解决方案4】:

        我知道我有点晚了,不知道你是否找到了答案。但我刚刚发现了如何做到这一点:

        reference.whereEqualTo("ordered",false).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
        
            if (queryDocumentSnapshots.isEmpty()) {
                Snackbar.make(mainContactsLayout, "No matches found", Snackbar.LENGTH_SHORT).show();
            } else {
        
                for (DocumentSnapshot documentSnapshot : queryDocumentSnapshots.getDocuments()) {
                    Snackbar.make(mainContactsLayout, documentSnapshot.getId(), Snackbar.LENGTH_SHORT).show();
                }
            }
        
        }
        });
        

        【讨论】:

          猜你喜欢
          • 2018-06-11
          • 2021-06-17
          • 1970-01-01
          • 1970-01-01
          • 2022-01-24
          • 2018-12-31
          • 1970-01-01
          • 2018-12-02
          相关资源
          最近更新 更多