Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add DisplayName with email + password authentication in Firebase? Android

Tags:

private void registerUser(){
String emailId = email.getText().toString().trim().toLowerCase();
String password = pass.getText().toString().trim();

firebaseAuth.createUserWithEmailAndPassword(emailId,password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressDialog.dismiss();
                if(task.isSuccessful()){
                    Toast.makeText(MainActivity.this,"Registration Successful",Toast.LENGTH_SHORT).show();

                    //show chatroom
                    finish();
                    startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
                }
                else{
                    Toast.makeText(MainActivity.this,"Registration Failed. Please try again",Toast.LENGTH_SHORT).show();
                }
            }
        });
}

I wish to add a username or display name to it but am unable to do so. I tried a few things but still no result. Kindly help me. I need this functionality for a project submission this week.

like image 949
Parth Mahajan Avatar asked Oct 01 '16 09:10

Parth Mahajan


2 Answers

This is definitely possibly but just not in the user creation method.

Once you've created your user (possibly in the addOnSuccessListener) you can use something similar to the following code to update the Users DisplayName:

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

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName("John Smith").build();

user.updateProfile(profileUpdates);

Hope this helps!

Edit: I previously said to add the code to the AuthStateListener, however, Frank's suggestion below to put it in the addOnSuccessListener is better/makes more sense so I have updated the answer to reflect this.

like image 144
edant92 Avatar answered Sep 23 '22 16:09

edant92


I just recently investigated this issue for my own implementation (SDK version 4.4.1). What I've found is that it works perfectly if you are sure to utilize the exact same task.result object from registration/login and not the object from the default instance.

Another work around that helped me is to have an email reference table in your FB DB like this:

{ "EmailRef": { "username1" : "email@ domain .com"}, {"username2" : "[email protected]"} }

And then to query for the username by the user's email (from auth.CurrentUser.Email) using a method like this:

public static void GetCurrentUserName(Firebase.Auth.FirebaseUser user)
{
    string message = "";
    DatabaseReference dbRef = FbDbConnection();
    FirebaseDatabase.DefaultInstance.GetReference("EmailRef").OrderByValue().EqualTo(user.Email).GetValueAsync().ContinueWith(task =>
    {
        if (task.IsFaulted)
        {
            message = "GetCurrentUserName encountered an error: " + task.Exception;
            ModalManager.BuildFireBaseDebugModal(message);
            Debug.LogError(message);
            return;
        }
        if (task.IsCanceled)
        {
            message = "GetCurrentUserName was canceled.";
            Debug.LogError(message);
            return;
        }
        if (task.IsCompleted)
        {
            foreach (DataSnapshot ss in task.Result.Children.AsEnumerable())
            {
                try
                {
                    if (ss.Value != null)
                    {
                        if (ss.Value.ToString() == user.Email)
                        {
                            message = "GetCurrentUserName was successful -- Email: " + user.Email + " Username: " + user.DisplayName;
                            Debug.LogError(message);
                        }
                    }
                    return;
                }
                catch (Exception ex)
                {
                    message = "GetCurrentUserName Exception: " + ex;
                    Debug.LogError(message);
                    return;
                }
            }
        }

    });
}
like image 24
Spiffai Avatar answered Sep 26 '22 16:09

Spiffai