Firebase setDisplayName of user while creating user Android-ThrowExceptions

Exception or error:

When creating a user, I want to be able to set his/her display name. How do I do this in Android? Here is an example of what I want to achieve:

mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful()){
                FirebaseUser.getCurrentUser().setDisplayName(mName); //I want to do this
            }
});

Assume all variables have been declared and/or initialized correctly.

How to solve:

You can set the user’s Firebase display name by writing the following three lines of code:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                    .setDisplayName(mName).build();

user.updateProfile(profileUpdates);

By doing so, your original code should look like this:

mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if(task.isSuccessful()){
            // Sign in is successful
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setDisplayName(mName).build();

            user.updateProfile(profileUpdates)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                  @Override
                  public void onComplete(@NonNull Task<Void> task) {
                      if (task.isSuccessful()) {
                          Log.d(TAG, "User profile updated.");
                      }
                  }
              });
        }
});

Official Firebase Documentation:
Firebase Update a User’s Profile

What the above code does is that when the user’s account is successfully created using Email and Password authentication, it will then sign-in the user.
Once the user is signed-in, you can access the user’s Firebase User Object Properties and set the display name property to any string you want.

This is great for testing the user’s profile name in Verification Emails.

Note: A Firebase User Object has a fixed set of basic properties—a unique ID, a primary email address, a name, and a photo URL. These basic properties are stored in the project’s User Database.
Furthermore, these properties can be updated programmatically.
However, you cannot add other properties to the Firebase User Object directly; instead, you can store any additional properties (i.e. user information) in your Firebase Realtime Database, and reference them from there.
(Firebase User Object Properties Doc)

###

I found the answer in the Firebase docs. I will quote it here: “If sign-in succeeded, the AuthStateListener runs the onAuthStateChanged callback. In the callback, you can use the getCurrentUser method to get the user’s account data.” Here is the link: https://firebase.google.com/docs/auth/android/password-auth#sign_in_a_user_with_an_email_address_and_password

So that means, if you do the above code (minus the FirebaseUser line), and then declare and initialize a Firebase AuthStateListener like shown below, you can set the user’s display name and then move on to any other activity you want:

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if(user!=null){
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                        .setDisplayName(mName).build();
            user.updateProfile(profileUpdates);
            Intent intent = new Intent(currentActivity.this, nextActivity.class);
            startActivity(intent);
        }
    }
};

And don’t forget to add the AuthStateListener in onResume() like so:

@Override
public void onResume(){
    super.onResume();
    mAuth.addAuthStateListener(mAuthListener);
}

Likewise, don’t forget to remove it in the onStop method like so:

@Override
public void onStop(){
    super.onStop();
    if(mAuthListener != null){
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

And done! You set the user’s display name so you can use it in other activities. This would be useful if you want to greet the user or access any other user data tied to the display name.

Leave a Reply

Your email address will not be published. Required fields are marked *