简体   繁体   中英

Why is FirebaseUser DisplayName not updating?

My Firebase authentification is Email based (Login and Registration requires just an email and password) that firebase manages afterwards.

My RegistrationActivity asks for a email, password, and Name too, because I want to later use it in my AccountActivity to have something like "Hello, [Name] " after being logged in. In order to have this name saved too, luckly, FirebaseUser already has a field called DisplayName, so all I have to do is update the user as soon as it's created ( createUserWithEmailAndPassword(...) automatically does the "login" too)

RegisterActivity relevant code:

firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            Toast.makeText(RegisterActivity.this, "Could not complete registration", Toast.LENGTH_SHORT).show();
                        } else {
                            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                                    .setDisplayName(name).build();
                            user.updateProfile(profileUpdates);
                            Toast.makeText(RegisterActivity.this, "Update complete", Toast.LENGTH_SHORT).show();

                            startActivity(new Intent(RegisterActivity.this, AccountActivity.class));
                            finish();

                        }


                    }
                });

However, as soon as the AccountActivity is started, the TextView which should contain the FirebaseUser DisplayName is null. And only AFTER pressing back, it opens the same AccountActivity AGAIN (why?) and the TextView is updated with the DisplayName. But the "back" functionality should just close the app altogether. What am I missing or doing wrong?

AccountActivity code:

public class AccountActivity extends AppCompatActivity {


private Button signOutBtn;

private FirebaseAuth firebaseAuth;
private FirebaseUser user;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);

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

    signOutBtn = (Button) findViewById(R.id.signOutBtn);
    signOutBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            firebaseAuth.signOut();
            startActivity(new Intent(AccountActivity.this, LoginActivity.class));
            finish();
        }
    });


    TextView accountTextView = (TextView) findViewById(R.id.AccountTextView);

    //TODO: if user.getDisplayName == null, get the NAME choice from input in RegisterActivity
    if (user.getDisplayName() == null)
    {
        accountTextView.setText("xxx");
    } else {
        accountTextView.setText(user.getDisplayName());
    }


}

@Override
public void onBackPressed() {
    finish();
}
}

My assumption was that while logged in, updating the currently logged in user won't change it until starting the Activity again, but I doubt that's the case since just pressing back while on the AccountActivty will first open it up again, with the proper DisplayName, then pressing back again will correctly close it.

Why is pressing back first not closing it, but instead it's updating the TextView to the correct DisplayName? Why is it not updating properly the first time? I'm sorry if I've not posted all the necessary info, please let me know.

To solve this, simply move the following line of code:

accountTextView.setText(user.getDisplayName());

Inside the callback, right after:

Toast.makeText(RegisterActivity.this, "Update complete", Toast.LENGTH_SHORT).show();

Trying to set the user name outside the callback does not make any sense since Firebase API's are asynchronous. So the quickest solution for solving this problem (as you already saw), was to use user.getDisplayName() only inside the onComplete() method. If you want to use it outside the callback, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM