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.
这是我的代码的一部分:
here part of my code:
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?
推荐答案
只需将一些示例代码添加到伊曼纽尔的答案中(谢谢!),其他寻求快速复制和粘贴的人就可以使用该代码:
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对象中找到,则上面的内容将尝试使用提供者提供的第一个显示名称和照片网址.
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.
奖金::对图像使用滑行: https://github.com /bumptech/glide .
Bonus: Using glide for images: https://github.com/bumptech/glide .
这篇关于firebaseAuth.getCurrentUser()返回null DisplayName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!