Android 如何等待Firestore完成,然后返回布尔结果?
当集合中的文档存在或不存在时,我希望返回True或False。但它总是返回falseAndroid 如何等待Firestore完成,然后返回布尔结果?,android,kotlin,google-cloud-firestore,Android,Kotlin,Google Cloud Firestore,当集合中的文档存在或不存在时,我希望返回True或False。但它总是返回false if (checkItemDeleted(post)) { // true, item still there } else { // false, item deleted } 我仍在学习中,谢谢您的帮助。您将在get呼叫完成之前返回结果。不要忘记这是异步的 尝试使用async and wait代替完整的侦听器。您不能等待异步加载的数据。需要数据的代码需要在完成侦听器中,或者从那里调用,或者使用K
if (checkItemDeleted(post)) {
// true, item still there
} else {
// false, item deleted
}
我仍在学习中,谢谢您的帮助。您将在get呼叫完成之前返回结果。不要忘记这是异步的
尝试使用async and wait代替完整的侦听器。您不能等待异步加载的数据。需要数据的代码需要在完成侦听器中,或者从那里调用,或者使用Kotlin的
wait
。
boolean result = false;
private boolean checkItemDeleted(Post post) {
mPostsCollection
.document(post.itemID)
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()){
if (task.getResult().exists()) {
// document exists
result = true;
} else {
// document not exists
result = false;
}
}
});
return result;
}