0

I have created a method that checks if a username already exists inside the Firestore database, but it doesn't seem to work,. Here's my code (registering the user does not work unless this returns true):

private boolean CheckExistingUser(String name)
{
    //get all users
    fstore.collection("Users").whereEqualTo("Username", name)
            .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            Toast.makeText(getApplicationContext(), "method clicked", Toast.LENGTH_SHORT).show();
         if (task.getResult().size()>0) {
             valid = false;
             progressBar.setVisibility(View.GONE);
             nameEditTxt.setError("Username already exists");
         }
         else valid = true;
        }
        else Toast.makeText(getApplicationContext(), "unknown error", Toast.LENGTH_SHORT).show();
    }
});
    return valid;
}

I noticed in the logcat the following error:

Listen for Query(target=Query(Users where Username == myusername order by name);limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

So I tried checking my rules in Firestore but I have no idea how to manipulate this since im very new to firestore

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
  allow read, write: if request.auth!=null;
   }
 }
}
Yassine
  • 25
  • 5
  • 1
    Data is loaded from Firebase (and most cloud APIs) asynchronously, so that it doesn't block the user from working with your app. While the data is being loaded your main code continues to run and your `return valid;` is executed. Then when the data is available, your `onComplete ` gets called and sets `valid`, but nobody will see it anymore. --- The solution is always the same: any code that needs the data from the database, has to be inside `onComplete`, be called from there, or be otherwise synchronized. – Frank van Puffelen Mar 25 '22 at 18:35

0 Answers0