Reputation: 13607
I'm following a simple code that checks if a document exists containing a specified email address. But if the email does not exist and no matching documents neither addOnCompleteListener
or addOnSuccessListner
or addOnFailureListener
are not getting called.
val db = Firebase.firestore
db.collection("Users").whereEqualTo("email", "[email protected]").get()
.addOnSuccessListener { QuerySnapshot ->
Log.d(TAG, "${QuerySnapshot.documents.size}")
}
.addOnCanceledListener {
Log.d(TAG, "Request was canceled!")
}
.addOnFailureListener { exception ->
Log.d(TAG, "$exception")
}
.addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result) {
Log.d(TAG, "${document.id}")
}
} else {
Log.d(TAG, "Error getting documents: ", task.exception)
}
}
As I understand this is not the expected behavior. Am I missing something here?
I am using the following as dependencies:
implementation platform('com.google.firebase:firebase-bom:29.0.0')
implementation 'com.google.firebase:firebase-firestore-ktx'
Update:
I tried bom:29.1.0
still the same behavior, I do have internet, mutations like add()
works fine
Upvotes: 1
Views: 109
Reputation: 138824
When your query yields no results, addOnFailureListener
won't be triggered, since the absence of some documents won't be considered an Exception. However, if your query will be rejected due to improper security rules, then an Exception will be thrown for sure.
You say that addOnCompleteListener
is also not triggered when your query doesn't return any documents. But I doubt it since you say that add()
works fine, meaning that you have an internet connection on the user device. Most likely it's triggered but you don't know it. Why? Because you aren't handling that case.
If you get no results, addOnCompleteListener
indeed fires, meaning that task.isSuccessful
returns true. This also means that the else part won't be evaluated. Since there are no documents, the for-each loop won't print anything. The best option that you have is to check the documents for existence:
.addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result) {
if(document.exists()) {
Log.d(TAG, "${document.id}")
} else {
Log.d(TAG, "Document doesn't exist.")
}
}
} else {
Log.d(TAG, "Error getting documents: ", task.exception)
}
}
Upvotes: 3