firebaseAuth.getCurrentUser() 返回 null DisplayName [英] firebaseAuth.getCurrentUser() return null DisplayName
问题描述
当我使用我的 google 帐户登录并使用 getDisplayName() 获取名称时,我的名称显示正确,但在 AuthStateListener 中却没有.
When I signIn with my google account and get the name with the getDisplayName(), my name appear correctly, but in the AuthStateListener doesn't.
这里是我的部分代码:
private void handleSignInResult(GoogleSignInResult result) {
Alert.dismissProgress();
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
if(acct != null) {
Log.i("NAME", acct.getDisplayName()); <-- RETURN MY NAME CORRECTLY
credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
fuser.linkWithCredential(credential).addOnCompleteListener(authResult);
} else {
//ERROR
}
} else {
//ERROR
}
}
但在我的 AuthStateListener 中
But in my AuthStateListener
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser nuser = firebaseAuth.getCurrentUser();
if (nuser != null) {
Log.i("NAME", nuser.getDisplayName()); <--- RETURN NULL
}
}
有人知道为什么会发生这种情况吗?
Somebody know why this can happen?
推荐答案
只是为了添加到 Ymmanuel 的答案(谢谢!)以及一些示例代码,供其他寻求快速复制和粘贴的人使用:
Just to add to Ymmanuel's answer (Thank you!) with some example code for anyone else looking for a quick copy and paste:
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
String displayName = user.getDisplayName();
Uri profileUri = user.getPhotoUrl();
// If the above were null, iterate the provider data
// and set with the first non null data
for (UserInfo userInfo : user.getProviderData()) {
if (displayName == null && userInfo.getDisplayName() != null) {
displayName = userInfo.getDisplayName();
}
if (profileUri == null && userInfo.getPhotoUrl() != null) {
profileUri = userInfo.getPhotoUrl();
}
}
accountNameTextView.setText(displayName);
emailTextView.setText(user.getEmail());
if (profileUri != null) {
Glide.with(this)
.load(profileUri)
.fitCenter()
.into(userProfilePicture);
}
}
如果最初没有在 User 对象中找到,上面将尝试使用提供者的第一个显示名称和照片 url.
The above will try to use the first display name and photo url from the providers if it wasn't initially found in the User object.
奖励:对图像使用 glide:https://github.com/bumptech/glide .
Bonus: Using glide for images: https://github.com/bumptech/glide .
这篇关于firebaseAuth.getCurrentUser() 返回 null DisplayName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!