为什么我的 else 块在我的 OnClickListener 中没有执行在 Java Android Studio 中?

huangapple go评论78阅读模式
英文:

Why is my else block not executing in my OnClickListener in java android studio

问题

我创建了一个功能,允许我的应用用户收藏商店。现在,如果用户已经收藏了一个商店,并再次点击按钮,它应该从Firestore数据库中删除记录。

我的代码只有在查询匹配并且任务成功时才有效,但不执行我的else部分。为什么呢?

下面的代码在查询和任务成功时运行正常,但如果没有匹配时,它不执行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 created a feature that lets my app users favorite shops. now if a user already favorited a shop and clicks on the button again it should delete the record from the firestore database.

my code works only if there is a match to the query and the task is successful, but doesnt execute my else part of the code. why is that?

and here isthe below code works fine when there is a match for the query and the task is successful, but when there isn't it doesnt execute the else part. anyone know why?

public void onClick(View view) {
Task ref = fStore.collection(&quot;Favorites&quot;)
.whereEqualTo(&quot;shopID&quot;, SID).whereEqualTo(&quot;usersID&quot;, UID)
.get()
.addOnCompleteListener(new OnCompleteListener&lt;QuerySnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
document.getReference().delete();
}
} else {
Map&lt;String, Object&gt; fav = new HashMap&lt;&gt;();
fav.put(&quot;shopID&quot;, SID);
fav.put(&quot;usersID&quot;, UID);
fav.put(&quot;ShopHeaderImg&quot;, sHI);
fav.put(&quot;ShopProfileImg&quot;, sPI);
fav.put(&quot;address&quot;, sA);
fav.put(&quot;costEst&quot;, sCost);
fav.put(&quot;country&quot;, sC);
fav.put(&quot;latitude&quot;, sLat);
fav.put(&quot;location&quot;, sL);
fav.put(&quot;name&quot;, sN);
fav.put(&quot;numTables&quot;, sNumTable);
fav.put(&quot;ratings&quot;, sR);
fav.put(&quot;summary&quot;, sSummary);
fav.put(&quot;timing&quot;, sT);
fStore.collection(&quot;Favorites&quot;).add(fav)
.addOnSuccessListener(new OnSuccessListener&lt;DocumentReference&gt;() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(DetailsActivity.this, &quot;Saved&quot;, Toast.LENGTH_SHORT).show();
}).addOnFailureListener(new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
Toast.makeText(DetailsActivity.this, &quot;Something went wrong&quot;, Toast.LENGTH_SHORT).show();
}
});
}
}
});

答案1

得分: 1

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) {
            }
        }
    }
}
英文:

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&lt;QuerySnapshot&gt; 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) {
}
}
}
}

huangapple
  • 本文由 发表于 2020年8月9日 11:29:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63322208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定