0

I get some information from users during the registration process. I want to register each username to be unique. I call my methods as follows.

if(!nameRegister.isEmpty() && !surnameRegister.isEmpty()
                        && !usernameRegister.isEmpty() && !emailRegister.isEmpty()
                        && !passwordRegister.isEmpty() && !passwordConfirmRegister.isEmpty()){
                if (passwordRegister.equals(passwordConfirmRegister)) {

                    isUsernameTaken = checkUsernameIsExist(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);

                    if(!isUsernameTaken)
                        isMailAuthenticationSuccess = createUserWithEmailAndPassword(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);

                }else{
                    passwordConfirm.setError("Passwords does not match.");
                    passwordConfirm.requestFocus();
                }

                if(isMailAuthenticationSuccess)
                    saveUserToFirebase(newUser);

            }

Its contents are as follows.

private boolean checkUsernameIsExist(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, final String passwordRegister) {

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    DocumentReference docIdRef = rootRef.collection("users").document(usernameRegister);
    docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    isUsernameTaken = true;
                    Log.d(TAG, "Document exists!");
                    Toast.makeText(Register.this, "User name already taken", Toast.LENGTH_LONG).show();
                } else {
                    Log.d(TAG, "Document does not exist!");
                    Toast.makeText(Register.this, "User can be taken", Toast.LENGTH_LONG).show();
                }
            } else {
                Log.d(TAG, "Failed with: ", task.getException());
            }
        }
    });
    return isUsernameTaken;
}

private boolean createUserWithEmailAndPassword(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, String passwordRegister) {

    auth.createUserWithEmailAndPassword(emailRegister, passwordRegister)
            .addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        email.setError("Mail is already taken");
                        email.requestFocus();
                    }else{
                        newUser = new User(nameRegister, surnameRegister, usernameRegister, emailRegister);
                        isMailAuthenticationSuccess  = true;
                        auth.signOut();
                        startActivity(new Intent(Register.this, Login.class));
                        finish();
                    }
                }
            });
    return  isMailAuthenticationSuccess;

}

private static void saveUserToFirebase(User newUser) {

        FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
        firebaseFirestore.collection("users").document(newUser.getUsername())
                .set(newUser)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "User add success.");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "user can not be added.", e);
                    }
                });
    }

Method can not add true boolean value to my variables. I think, addOnCompleteListener did not end before when assign to value my booleans.

However, if the user name can be obtained after user name control, user authentication is successful, but writing to Firebase does not take place. What could be the reason for this? I am waiting for your help.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
ccanozerr
  • 23
  • 7
  • Hi @Frank van Puffelen, my question is i call my saveUserToFirebase method succesfully. I can add my listeners also add logs inside of them. But my listener can not work and can not save my object to cloud firestore. Why is not working? If you have any idea please give me an advice. – ccanozerr Jul 09 '20 at 13:25
  • If you execute the code in a debugger and place breakpoints on both lines you'll see that your `return isUsernameTaken;` runs before the `isUsernameTaken = true;`. I linked a number of questions that explain why that is, why you can't return a value that is asynchronously loaded, and how you can work around this. – Frank van Puffelen Jul 09 '20 at 14:14
  • Hi again Frank, many thanks for your help. I will check your linked questions. Have a nice day. – ccanozerr Jul 10 '20 at 06:03
  • Frank first link is useful for me. Thank you so much for helping :) – ccanozerr Jul 10 '20 at 10:06

2 Answers2

0

call this method "createUserWithEmailAndPassword" in onSuccess of this method "checkUsernameIsExist" and make sure that your return type is void.

Harsh Suvagiya
  • 106
  • 1
  • 3
  • Hi, this is work but i tried before when i ask. I can not triggered add my user to firebase. I can call saveUserToFirebase method everything seems fine but can not trigger addOnCompleteListener or addOnSuccessListener. When i call my saveUserToFirebase method inside of createUserWithEmailAndPassword's onComplete nothing gonna happen. – ccanozerr Jul 09 '20 at 12:01
0

A simple suggestion is that you call the saveUserToFirebase(newUser) inside the createUserWithEmailAndPassword() function just before you set isMailAuthenticationSuccess = true;

Or call that function inside

if(!isUsernameTaken){

isMailAuthenticationSuccess = createUserWithEmailAndPassword(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);

if(isMailAuthenticationSuccess) saveUserToFirebase(newUser); }

That might solve your problem.

Or you can try the below code

if(!nameRegister.isEmpty() && !surnameRegister.isEmpty() && !usernameRegister.isEmpty() && !emailRegister.isEmpty() && !passwordRegister.isEmpty() && !passwordConfirmRegister.isEmpty()){
    if (passwordRegister.equals(passwordConfirmRegister)) {
        checkUsernameIsExist(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);
    }else{
        passwordConfirm.setError("Passwords does not match.");
        passwordConfirm.requestFocus();
    }
}


//checkUsernameIsExist
private void checkUsernameIsExist(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, final String passwordRegister) {
    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    DocumentReference docIdRef = rootRef.collection("users").document(usernameRegister);
    docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                isUsernameTaken = true;
                Log.d(TAG, "Document exists!");
                Toast.makeText(Register.this, "User name already taken", Toast.LENGTH_LONG).show();
            } else {
                Log.d(TAG, "Document does not exist!");
                Toast.makeText(Register.this, "User can be taken", Toast.LENGTH_LONG).show();
                createUserWithEmailAndPassword(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);
            }
        } else {
        Log.d(TAG, "Failed with: ", task.getException());
        }
        }
    });
}
// createUserWithEmailAndPassword
private void createUserWithEmailAndPassword(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, String passwordRegister) {
    auth.createUserWithEmailAndPassword(emailRegister, passwordRegister)
    .addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(!task.isSuccessful()){
                email.setError("Mail is already taken");
                email.requestFocus();
            }else{
                newUser = new User(nameRegister, surnameRegister, usernameRegister, emailRegister);
                saveUserToFirebase(newUser);
                isMailAuthenticationSuccess  = true;
                auth.signOut();
                startActivity(new Intent(Register.this, Login.class));
                finish();
            }
        }
    });
}

private static void saveUserToFirebase(User newUser) {
    FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseFirestore.collection("users").document(newUser.getUsername())
    .set(newUser)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "User add success.");
            Toast.makeText(Register.this, "User added successfully", Toast.LENGTH_LONG).show();
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "user can not be added.", e);
            Toast.makeText(Register.this, "Couldn't add User. Try again later.", Toast.LENGTH_LONG).show();
        }
    });
}
BEAGLE
  • 343
  • 3
  • 10
  • Hi @BEAGLE, i tried these almost 5 minutes ago thank you :) When i call my saveUserToFirebase method inside of createUserWithEmailAndPassword's onComplete nothing gonna happen. I have no idea i can call method and this is the right way i think. But it does not work. If you have any other idea im waiting thank you again. – ccanozerr Jul 09 '20 at 12:03
  • Try adding few toasts inside the saveuser() to see the how far the code is executing. See if newUser.getUsername() returns value. can be referencing issue. – BEAGLE Jul 09 '20 at 12:12
  • Try adding few toasts inside the saveuser() to see the how far the code is executing. See if newUser.getUsername() returns value. can be referencing issue. – BEAGLE Jul 09 '20 at 12:13
  • Hi, i add Logs but i can not see any logs. It looks like my saveUserToFirebase method can be called but cant do anything :/ I can not understand why this is happening. – ccanozerr Jul 09 '20 at 12:24