首页 > 解决方案 > 如果用户尚未登录,如何为 getDisplayName() 写 if 语句?

问题描述

我在运行我的应用程序时遇到了这个问题:

尝试在空对象引用上调用虚拟方法 java.lang.String com.google.firebase.auth.FirebaseUser.getDisplayName()

我想制作一个用户无需先登录即可浏览的应用程序。if 语句里面怎么name.setText("hi, " + currentUser.getDisplayName());写 if 语句的编码我应该写什么?

这是我的MainActivityjava类:

@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();
}
}

标签: javaandroidfirebase-authentication

解决方案


检查 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());

推荐阅读