跨活动访问用户信息 Firebase Android

Access user information across activities Firebase Android

在一个 activity 中,我正在登录用户,然后它转到另一个 activity,在那里欢迎用户。我正在使用内置的 Firebase 方法通过 email/password 登录用户。我在 Firebase 数据库中有 UID,它与一个名称相关联。我只是在 Firebase 中手动输入用户,稍后将实施注册 activity。如何访问第二个用户的UIDactivity?

您应该将其保存在 SharedPreferences 中并在第二个 activity 中检索它,或者通过 Intent 对象将其传递到第二个 Activity 中。

SharedPreferences 是在应用程序中持久存储数据的更简单方法之一。存储在 SharedPreferences 中的数据几乎可以从应用程序的任何位置进行检索和修改。数据将在 phone 次重启,甚至应用程序卸载后继续存在,因为它可以被系统备份。 Here is the official explanation. And here 是一个很好的教程。

除了传递 uid,您还可以 use an auth state listener to detect the user in each activity。从该文档页面:

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        } else {
            // User is signed out
            Log.d(TAG, "onAuthStateChanged:signed_out");
        }
        // ...
    }
};

此代码通常会进入您从中派生活动的基 class。

只需使用

FirebaseAuth mAuth;

mAuth = FirebaseAuth.getInstance();

FirebaseUser user = mAuth.getCurrentUser();

String UID = user.getUid();

它会自动从以前的活动中获取用户。