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
CodePudding user response:
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)
}
}
CodePudding user response:
I tested the code again, added Frank's suggested log statement, strangely now it works. Before I really saw debugger jumping from one task handler to another and exit the function.
I think this is probably a caching issue in Android Studio, because before adding Frank's suggested log statement I changed the app icon(changes inside src/main/res/
) which may have result in app rebuild.
I think it is better to Clean Project
and rerun the app in case you came across such a weird behavior or even Invalidate Cache
and restart if Clean Project
does not work out.