java - 如何知道 Firestore 查询快照中是否存在数据?

标签 java android firebase google-cloud-firestore

这是我想要获取数据并了解数据是否存在的代码。 问题是,如果数据存在,它会运行 { 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();
                    }
                }
            }
        }
    });

最佳答案

您需要直接在 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() 用于在 exists() 时处理监听器中的成功或失败。在 QueryDocumentSnapshot 的对象上调用时的方法扩展 DocumentSnapshot 的类类返回:

true if the document existed in this snapshot.

关于java - 如何知道 Firestore 查询快照中是否存在数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50618219/

相关文章:

java - 窗口/舞台失去焦点时的事件

java - Android 简单选项卡和工具栏

android - Linux 蓝牙找不到具有 UUID 的 Android 服务

node.js - ionic+firebase+elasticsearch 无法使用 elasticsearch.js 进行身份验证

java - 将 JButton 添加到 JTable

java - Collections.unmodifiableSet() 在 Java 中做了什么?

android - 拉动刷新不适用于 firebaseRecyclerAdapter

ios - Firebase:Googleservices-info.plist 未下载

java - 以前凌乱的任务仍然有一些我不明白的错误

android - 是否可以在 textview 中缩放 drawableleft 和 drawableright?