Firestore query on android studio not working as expected

Viewed 99
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("User")
    .whereEqualTo("username", user)
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if(task.isSuccessful()) {
                Toast.makeText(Signup.this, "Username already exists please try again", Toast.LENGTH_SHORT).show();
            }
            else {
                User newUser = new User(user, pass, mail);
                CollectionReference dbUser = db.collection("User");
                dbUser.add(newUser);
                Intent intent = new Intent(Signup.this, StartScreen.class);
                startActivity(intent);
        }
    }
});

In the above code no matter what I change the value of the user to be it is going into the task.isSuccessful() if statement. The only two username values under that collection are "testuser" and "umair".

enter image description here

enter image description here

I have not used Firebase before so it very well could be an obvious error I am glazing over.

1 Answers

If the task is successful doesn't mean that the username already exists. It means that the Firebase servers didn't reject your read operation. So if the task is successful you can read/add the desired data, otherwise, an exception will be thrown. So your code should look like this:

if(task.isSuccessful()) {
    for (DocumentSnapshot document : task.getResult()) {
        if (document.exists()) {
            String userName = document.getString("username");
            Log.d("TAG", "username already exists.");
        } else {
            Log.d("TAG", "username doesn't exist.");

            User newUser = new User(user, pass, mail);
            CollectionReference dbUser = db.collection("User");
            dbUser.add(newUser);
            Intent intent = new Intent(Signup.this, StartScreen.class);
            startActivity(intent);
        }
    }
} else {
    Log.d("TAG", task.getException().getMessage());
}
Related