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

Sam*_*ari 5 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();
                    }
                }
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

Ale*_*amo 4

您需要exists()直接在对象上使用方法,QueryDocumentSnapshot如下所示:

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();
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

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

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