Incorrect behaviour by Firestore whereEqualto() query in android app

Viewed 38

My database consists of a collection called songs which has fields: artist, email, link and name. At the moment the email field in all documents is an empty string. Here is a pic of one of the entries.

Here is the query that I'm running in my android app:

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
        firebaseAuth = FirebaseAuth.getInstance();

        FirebaseFirestore db = FirebaseFirestore.getInstance();

        TextView userinfo = (TextView)findViewById(R.id.link);
        FirebaseUser userauth = firebaseAuth.getCurrentUser();

db.collection("songs").whereEqualTo("email",userauth.getEmail()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>(){
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Document found in the offline cache
            userinfo.setText("User found");
        } else {
           userinfo.setText("User not found");
        }
    }
});


    }

The TextView is printing User found even though all the email entries are empty strings. The expected behavior is User not found.

1 Answers

If you only check if a Task is successful it doesn't mean that you get results. It means that your query is completed with no errors. If you need to know if the query returns the desired result, then you should check that in code:

if (task.isSuccessful()) {
    QuerySnapshot snapshot = task.getResult();
    if (snapshot.isEmpty()) {
        userinfo.setText("User not found");
    } else {
        userinfo.setText("User found");
    }
} else {
    Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}

The "User not found" message will be set to your userinfo TextView.

Related