我在运行我的应用程序时遇到了这个问题:尝试在空对象引用上调用虚拟方法 java.lang.String com.google.firebase.auth.FirebaseUser.getDisplayName()我想制作一个用户无需先登录即可浏览的应用程序。如何将name.setText("hi, " + currentUser.getDisplayName());if 语句放在里面 我应该在 if 语句的编码中写什么?这是我的MainActivityjava类:@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name=findViewById(R.id.name); // //display customer's account name name.setText("hi, " + currentUser.getDisplayName()); //ini firebaseAuth = FirebaseAuth.getInstance(); currentUser = firebaseAuth.getCurrentUser(); databaseReference = FirebaseDatabase.getInstance().getReference("Cust");@Overridepublic boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_option,menu); return true;}@Overridepublic boolean onOptionsItemSelected(@NonNull MenuItem item) { int id= item.getItemId(); if (id == R.id.logout){ logout(); return true; } else if (id==R.id.login){ login(); return true; } return super.onOptionsItemSelected(item);}private void login() { Intent intent= new Intent(this,LoginActivity.class); startActivity(intent);}private void logout() { FirebaseAuth.getInstance().signOut(); Intent intent = new Intent(MainActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish();}}
1 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
检查 currentUser 是否不为空:
if (currentUser != null) name.setText("hi, " + currentUser.getDisplayName());
而且,在您的代码中,您在从 firebase 初始化它getDisplayName 之前要求它,因此它始终为空:
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Cust");
if (currentUser != null) name.setText("hi, " + currentUser.getDisplayName());
添加回答
举报
0/150
提交
取消