I wanted to fetch the user details like name, email id and image when a user logs in with google on the navigation drawer header. I successfully authenticated the user via Google sign in but the app crashes while setting name email and picture on the drawer.
The error shows:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.replace(java.lang.CharSequence, java.lang.CharSequence)' on a null object reference
And the code related to it is
FirebaseDatabase.getInstance().getReference(Constants.USER_KEY).child(mFirebaseUser.getEmail().replace(".", ","))
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null){
Users users = dataSnapshot.getValue(Users.class);
Glide.with(MainActivity.this)
.load(users.getPhotoUrl())
.into(mDisplayImageView);
mNameTextView.setText(users.getUser());
mEmailTextView.setText(users.getEmail());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Is there any way to fix this issue? Or an alternative way?
答案 0 :(得分:1)
您的错误消息会告诉您代码中的确切问题。因此,您要调用replace()
方法on a null object reference
。这意味着mFirebaseUser.getEmail()
返回null
。要解决此问题,您需要在实际使用它之前实例化mFirebaseUser
对象,如下所示:
FirebaseUser mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
要获取用户电子邮件,只需使用以下代码行:
if (mFirebaseUser == null) {
String userEmail = mFirebaseUser.getEmail();
}