java - 为什么我的 else 块没有在 java android studio 的 OnClickListener 中执行
问题描述
我创建了一个功能,让我的应用程序用户最喜欢的商店。现在,如果用户已经收藏了一家商店并再次单击该按钮,它应该从 Firestore 数据库中删除该记录。
我的代码仅在与查询匹配并且任务成功时才有效,但不执行我else
的部分代码。这是为什么?
query
当和匹配时,下面的代码可以正常工作task is successful
,但是当不匹配时,它不会执行该else
部分。有谁知道为什么?
public void onClick(View view) {
Task ref = fStore.collection("Favorites")
.whereEqualTo("shopID", SID).whereEqualTo("usersID", UID)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
document.getReference().delete();
}
} else {
Map<String, Object> fav = new HashMap<>();
fav.put("shopID", SID);
fav.put("usersID", UID);
fav.put("ShopHeaderImg", sHI);
fav.put("ShopProfileImg", sPI);
fav.put("address", sA);
fav.put("costEst", sCost);
fav.put("country", sC);
fav.put("latitude", sLat);
fav.put("location", sL);
fav.put("name", sN);
fav.put("numTables", sNumTable);
fav.put("ratings", sR);
fav.put("summary", sSummary);
fav.put("timing", sT);
fStore.collection("Favorites").add(fav)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(DetailsActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}).addOnFailureListener(new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
Toast.makeText(DetailsActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
});
解决方案
I think you are misunderstanding what task.isSuccessful()
means. That method will return true if there were no errors during the execution of the query. A query that returns no documents isn't an error. That situation is perfectly normal, and considered successful. An error only happens when you try to execute a query that Firestore can't actually run.
If you want to check if a query returned no documents, you should look at the QuerySnapshot contained in the task results. It has a method isEmpty() that will tell you if there are documents.
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshot = task.getResult();
if (querySnapshot.isEmpty()) {
// put code here to deal with no documents in the result
}
else {
// put code here to deal with documents present in the result
for (QueryDocumentSnapshot document : querySnapshot) {
}
}
}
}
推荐阅读
- git - 将分叉的 repo 与原始 repo 的测试分支合并
- .net - EF Core 中的自动计算字段
- reactjs - 过滤具有多个字符串值的对象
- python - python .index() 和 .find() 之间的时间复杂度差异
- payment-gateway - 不同的提供商支付佣金
- vba - VBA + Pivot:在过滤器更改时运行脚本,但在枢轴启动刷新之前
- c# - 我可以从 ac# 9 记录的自动生成方法中隐藏敏感属性值吗?
- python - 从空格分隔的字符串创建 Pandas DataFrame
- time-complexity - 这些代码的时间和空间复杂度
- azure-devops - 如何在 azure devops 中知道分叉存储库的源存储库?