0

I have an EditText where I type an username. After I click "REGISTER", a function processes the username to check if it already exists:

public boolean usernameExists (String username) {

    database.collection("users").document(username).get()
    .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete (@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                usernameExists_result = task.getResult().exists();
            }
            else {
                task.getException().printStackTrace();
            }
        }
    });
    return usernameExists_result;

}

where database and usernameExists_result are both fields. Of course, since the username is the documentID, this function should return true if the document (and so the username) exists, and false if it doesn't.

Now, the problem is the function - apart from the first call - always returns the value that it should have returned on the previous call.

For example, if on the first call the function returns true because the username already exists, and then I type another username that doesn't exist, the function will also return true. On the next call, it will return false, because that it what it should have returned on the previous call. And on the next call, it will return whatever it should have returned on the previous, and so on.

Does anyone have an explanation for this behavior? I can provide whatever info is needed.

  • Data is loaded from Firestore (and most modern web APIs) asynchronously. If you run in a debugger and set breakpoints, you'll see that your `return usernameExists_result` runs before `usernameExists_result = task.getResult().exists()` ever gets executed. For this reason any code that needs the data from Firestore must be inside `onComplete` or be called from there. See https://stackoverflow.com/a/51002413/209103 – Frank van Puffelen Jan 31 '21 at 00:45

1 Answers1

0

Firebase is not working like this. Try to avoid making a methood boolean INSTEAD just just go on.

Example here:- your button

private void setBtnRegister(){
   btnRegister.setOnClickListener(new View.OnClickListener(){
   @Override
   public void onClick(View view){
          //Check all exception here. (incase editext is null)
          //and then put the code here instead that method boolean
          database.collection("users").document(username).get()
          .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
          @Override
          public void onComplete (@NonNull Task<DocumentSnapshot> task) {
          if (task.isSuccessful()) {
                //Success, maybe go next step
          }
          else {
                //Fail 
          }
        }
    });
   }
   });
}
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46