java - 如果用户尚未登录,如何为 getDisplayName() 写 if 语句?
问题描述
我在运行我的应用程序时遇到了这个问题:
尝试在空对象引用上调用虚拟方法 java.lang.String com.google.firebase.auth.FirebaseUser.getDisplayName()
我想制作一个用户无需先登录即可浏览的应用程序。if 语句里面怎么name.setText("hi, " + currentUser.getDisplayName());
写 if 语句的编码我应该写什么?
这是我的MainActivity
java类:
@Override
protected 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");
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_option,menu);
return true;
}
@Override
public 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();
}
}
解决方案
检查 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());
推荐阅读
- r - R找到有条件的正确名称
- c++ - 为什么 std::forward_list::empty 有 [[nodiscard]] 而 std::forward_list::max_size 没有?
- java - While 循环终止而不改变条件的值
- python - 确定 pandas 序列的元素是否包含不同序列的元素作为子字符串
- javascript - 如何从一个输入标签传递两个“名称”以在服务器中访问
- python - pandas 的 .query() 不接受我使用 like 'XXX%' 来表达 startwith 的表达
- cmake - 从 MSVC 2019 内置 CMake 配置英特尔编译器
- c# - 委托问题,名称在当前上下文中不存在?
- python - 仅从数据框中选择每个月的最后一周 - Python/Pandas
- llvm - 将现有函数的参数放在对 LLVM 函数传递中另一个函数的调用中