登录后在Android Studio中显示Firebase用户名吗?

时间:2019-03-12 02:51:42

标签: android firebase firebase-authentication

XML前端是一个简单的文本视图,其默认名称为John Smith。您如何更改它以在每次登录时显示用户名?

后端使我感到困惑,我在哪里将Firebase信息放入Java活动中?

public class ProfileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Profile");


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        onBackPressed();
        return super.onOptionsItemSelected(item);

    }

    @Override
    public Context createDisplayContext(Display display) {
        return super.createDisplayContext(display);
    }
}

1 个答案:

答案 0 :(得分:1)

我通常会将代码做到这一点,放在onStart中,该代码在每次活动开始时都会运行。如documentation所示,您可以在此处使用FirebaseAuth.getInstance().getCurrentUser()获取当前已签名的用户,也可以使用AuthStateListener

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Profile");

    FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // TODO: set user.getDisplayName() to view here
            }
        }
    };
}