gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:26:01 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com