我不断收到此错误:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' 当我运行代码时:
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity
{
private CircleImageView settingsDisplayProfileImage;
private TextView settingsDisplayname;
private TextView settingsDisplayStatus;
private Button setingsChangeProfileImage;
private Button settingsChangeStatus;
private DatabaseReference getUserDataReference;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
String online_user_id = mAuth.getCurrentUser().getUid();
getUserDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(online_user_id);
settingsDisplayProfileImage = (CircleImageView) findViewById(R.id.settings_profile_image);
settingsDisplayname = (TextView) findViewById(R.id.settings_username);
settingsDisplayStatus = (TextView) findViewById(R.id.settings_user_status);
setingsChangeProfileImage = (Button) findViewById(R.id.settings_change_profile_image_button);
settingsChangeStatus = (Button) findViewById(R.id.settings_profile_status);
getUserDataReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String name = dataSnapshot.child("user_name").getValue().toString();
String status = dataSnapshot.child("user_status").getValue().toString();
String image = dataSnapshot.child("user_image").getValue().toString();
String thumb_image = dataSnapshot.child("user_thumb_image").getValue().toString();
settingsDisplayname.setText(name);
settingsDisplayStatus.setText(status);
}
@Override
public void onCancelled( DatabaseError databaseError) {
}
});
}
}
我尝试了一些解决方案,但似乎没有任何效果。 这段代码似乎是问题所在,但我不知道如何解决该错误:字符串online_user_id = mAuth.getCurrentUser()。getUid();
我的logcat出现此错误:原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()'< / p>
答案 0 :(得分:0)
在获取Uid之前,请检查用户是否已登录。我知道您认为自己已在evrytime中登录,您“正在运行代码”,但这是确保您已登录的一种好习惯。
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
} else {
// No user is signed in
}
有关管理用户的更多信息,请参考链接:Official doc
如果auth对象尚未完成初始化,getCurrentUser()也可能返回null。使用AuthStateListener可以更好地处理这种情况。