2

I am working on an android application that involves user firebase auth for user sign up. The sign up works but I want to add username to database by implementing it in .then() but my android studio keeps giving "unresolved method then(?)". I am also using catch but that seems to work fine.The code I am writing is as following where firebaseAuth is an object of type FirebaseAuth:

            firebaseAuth.createUserWithEmailAndPassword(email,password)
                .then( (u) => {
                        //Implementation of then
                })
                .catch(error => {
                switch (error.code) {
                    case 'auth/email-already-in-use':
                        EmailWarning.setText("Email already in use");
                    case 'auth/invalid-email':
                        EmailWarning.setText("Invalid Email");
                    case 'auth/weak-password':
                        PasswordWarning.setText("Password should be 8 characters or longer");
                    default:
                        PasswordWarning.setText("Error during sign up");
                }
        });

I found a similar problem in following link but even after trying this, it's not working.

I looked further into the firebase documentation and found another implementation which uses on complete listener here however the error codes described in this documentation doesn't seem to work with it.

Update 1: I ended up implementing on complete listener as following:

            firebaseAuth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            FirebaseUser user = firebaseAuth.getCurrentUser();
                            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                                    .setDisplayName(Username)
                                    .build();

                            user.updateProfile(profileUpdates);
                        }
                        else {
                            // If sign up fails, display a message to the user.
                            switch (task.getException()) {
                                case "auth/email-already-in-use":
                                    EmailWarning.setText("Email already in use");
                                case "auth/invalid-email":
                                    EmailWarning.setText("Invalid Email");
                                case "auth/weak-password":
                                    PasswordWarning.setText("Password should be 8 characters or longer");
                                default:
                                    PasswordWarning.setText("Error during sign up");
                            }
                        }

                    }
                });

Now the user adding part works fine but the exception handler doesn't work with strings so I can't find a way to work with error codes given on firebase documentation

  • 1
    I think you want `task.getError()`, I dont think `task.getException()` exists -> https://firebase.google.com/docs/reference/android/io/fabric/sdk/android/fabric/services/concurrency/Task?hl=en – ewizard May 03 '20 at 13:30
  • and `isFinished()` instead of `isSuccessful()` - `isFinished()` should only be called if it finishes without error, from same doc link above. – ewizard May 03 '20 at 13:35
  • I would log `task.getError()` to make sure you know what the strings are, you are probably only getting into the error block because `isSuccessful()` isn't a function. – ewizard May 03 '20 at 13:36
  • `task.getError()` will return a `Throwable` -> https://firebase.google.com/docs/reference/android/io/fabric/sdk/android/fabric/InitializationException - it looks like you can use `getMessage()` or `toString()` to get string representations of the error. To get the actual `Throwable` you can use `getCause()` - this would return an exception object like `InitializationException`, and if you know which exceptions are possible you can use `==` with those. – ewizard May 03 '20 at 13:52

3 Answers3

3

I wasn't able to find a solution to .then() issue but after searching more into getExceptions() I found a solution at this link. Now my current implementation looks as following:

            firebaseAuth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            FirebaseUser user = firebaseAuth.getCurrentUser();
                            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                                    .setDisplayName(Username)
                                    .build();

                            user.updateProfile(profileUpdates);

                            OpenApp();
                        }
                        else {
                            // If sign up fails, display a message to the user.

                            String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();
                                if (task.getException() instanceof FirebaseAuthUserCollisionException)
                                    EmailWarning.setText("Email already in use");
                                else if(task.getException() instanceof FirebaseAuthInvalidCredentialsException)
                                    EmailWarning.setText("Invalid Email");
                                else if(task.getException() instanceof FirebaseAuthWeakPasswordException)
                                    PasswordWarning.setText("Password should be 8 characters or longer");
                                else
                                    PasswordWarning.setText("Error during sign up");
                            }
                        }
                });

Also found another alternate implementation by try catch and and getException().getErrorCode() here.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
0

I found this in the docs for you:

firebaseAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "createUserWithEmail:success");
                FirebaseUser user = mAuth.getCurrentUser();
                updateUI(user);
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
                updateUI(null);
            }

            // ...
        }
    });

Looks like you need to use .addOnCompleteListener

Doc -> https://firebase.google.com/docs/auth/android/password-auth

ewizard
  • 2,801
  • 4
  • 52
  • 110
  • I tried this one, I am able to resolve the username adding issues with it but the error codes described in the other firebase document (which I am using in catch) doesn't work with it or I am unable to figure out right format of condition for it – Shaheryar Ali May 03 '20 at 13:05
  • show me what you tried, you can edit your post with the additional info – ewizard May 03 '20 at 13:06
  • 1
    OK, I added the new implementation – Shaheryar Ali May 03 '20 at 13:25
0

I have found my issue with the help of (task.getException()) So I hope maybe it will helpful for resolving your issue.

firebaseAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
               
            } else {

               Log.d("---->",""+task.getException());
            }

           
        }
    });
Ali Raza Khan
  • 181
  • 1
  • 4