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