0

I want to returning True or False when document in collections is exists or not. But it's always return false.

if (checkItemDeleted(post)) {
   // true, item still there
} else {
  // false, item deleted
}
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;
    }

I'm still learning, thanks for help.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Gesa
  • 11
  • 2
  • You cannot wait for data that is asynchronously loaded. Code that needs the data need to be inside the completion listener, or be called from there, or use Kotlin's `await`. – Frank van Puffelen Apr 23 '21 at 15:43

1 Answers1

1

You are returning the result before the get call is done. Don't forget that is async.

Try using async and await instead of the complete listener.

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18