Firebase用户displayName为null问题:注册与读取代码排查
问题原因分析与解决方案
你的displayName返回null主要是异步操作的时序问题,加上一些多余代码导致的,具体来看:
核心问题点
多余的二次登录操作
调用createUserWithEmailAndPassword成功后,Firebase已经自动让新注册的用户登录了,不需要再调用signInWithEmailAndPassword。这步多余操作不仅没用,还会干扰后续的用户信息更新流程。未等待
updateProfile异步操作完成就跳转页面userFire.updateProfile(updateprofile)是异步执行的,它不会立刻修改用户的Profile信息。你在注册成功后直接调用SingIn(view)跳转到Profile页面,此时Profile的更新操作可能还没完成,所以读取getDisplayName()时还是初始的null值。
修改后的注册代码
rAuth.createUserWithEmailAndPassword(username,password_user).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ // 注册成功后用户已自动登录,无需二次登录 FirebaseUser userFire = FirebaseAuth.getInstance().getCurrentUser(); UserProfileChangeRequest updateprofile = new UserProfileChangeRequest.Builder() .setDisplayName(userName.getText().toString().trim()) .setPhotoUri(userphotourl).build(); // 等待updateProfile完成后再跳转页面 userFire.updateProfile(updateprofile).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> updateTask) { if (updateTask.isSuccessful()) { // 确认Profile更新完成后再跳转到个人页面 SingIn(view); } else { // 处理Profile更新失败的情况 Toast.makeText(getApplicationContext(),"更新用户信息失败",Toast.LENGTH_SHORT).show(); } } }); } else{ Toast.makeText(getApplicationContext(),"注册失败,请检查网络连接",Toast.LENGTH_SHORT).show(); } } });
额外优化建议
在Profile页面读取用户信息时,可以添加一个Auth状态监听,实时同步用户信息的变化,避免页面加载时异步更新还没完成的情况:
// 在ProfileActivity的onCreate中添加 FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { ProfileName.setText(user.getDisplayName()); ProfileEmail.setText(user.getEmail()); if(user.getPhotoUrl() != null){ ProfileImage.setImageURI(user.getPhotoUrl()); } } } });
这样就能确保用户信息更新完成后,页面能及时刷新最新的displayName和photoUri了。
内容的提问来源于stack exchange,提问作者ILHOM4IK
相关产品推荐
相关产品推荐

