Reputation: 47
My intention here is to display a Toast message if the user inputs an email/password combination that does not match any of the user profiles in the Firestore database.
I've been trying this multiple ways, but it refuses to call the code within "if (!document.exists()))." I've tried omitting "(!document.exists) and just using "else" - nothing.
Everything else works great. "if (document.exists())" happily returns the info and logs in. Please let me know if I need to include more info!
FirestoreRepository:
public void queryUserByEmailPassword(String email, String password) {
Query userQuery = userColRef.whereEqualTo("email", email).whereEqualTo("password", password);
userQuery.get().addOnCompleteListener(querySnapshotOnCompleteListener);
}
LoginViewModel:
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot doc : task.getResult()) {
if (!document.exists()) { // this code will NOT execute
Log.d(TAG, "Error getting documents: ", task.getException());
return;
} else { // this code executes flawlessly
user = doc.toObject(User.class);
currentUser.setValue(user);
doesUserExist.setValue(true);
repo.signIn(user.getEmail(), user.getPassword());
}
}
}
}
Upvotes: 0
Views: 38
Reputation: 317427
It looks like you're assuming that an error with the query will result in a document to show up in a QueryDocumentSnapshot
. That's not the way it works. If there's an error with the query, then task.isSuccessful()
will return false. You're currently not checking that case.
If you query returns no documents, then your for
loop will not execute at all. It is not considered an "error" to get zero documents. If you need to know if there are no documents in the result, you should check that the QuerySnapshot contains no documents:
if (task.isSuccessful()) {
QuerySnapshot qs = task.getResult();
if (qs.size() == 0) {
// the query returned no documents - decide what to do
}
else {
// iterate the documents here
for (QueryDocumentSnapshot snapshot : qs) {
}
}
}
else {
// there was an error, use task.getException() to figure out what happened
}
Upvotes: 1