且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firebase getCurrentUser 在新的 android 活动中返回 null

更新时间:2022-12-19 21:18:28

我今天遇到了同样的问题.在解决了你的问题后,我再次检查了我的代码,我发现了我的错误.我在第一个活动结束时使用了 signout().在我删除后,我的代码工作正常.

I had this same problem today. After going through your problem i again checked my code and i found my mistake.I was using signout() at the end of my 1st activity. After i removed that my code is working fine.

我正在使用文档中给出的 authStateListener.在 onCreate 方法中设置侦听器.函数 getCurrentUser() 设置一个后台任务来获取当前用户,因此监听器很重要.

I am using the authStateListener given in the documentation.Set the listener in onCreate method. Funtion getCurrentUser() sets an background task to fetch current user so the listener is important.

onCreate()

mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                String UserId = mCurrentUser.getUid();
                mCurrentUser = user;
                Toast.makeText(ListActivity.this, "USER ID
"+mUserId,Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(ListActivity.this, "no id got", Toast.LENGTH_SHORT).show();
            }

        }
    };

在 onStart 或 onResume 方法中,我正在调用 getCurrentUser() 方法

In onStart or onResume method i am calling the getCurrentUser() method

onResume()

 mCurrentUser = mAuth.getCurrentUser();

在连接速度慢的情况下

mCurrentUser = user;

在 onCreate() 中会解决这个问题.就我个人而言,我更喜欢在 onStart() 中使用 getcurrentuser 方法,以便在应用程序在慢速互联网上运行时有时间获取用户.

in onCreate() will take care of the problem. Personally i prefer to use getcurrentuser method in onStart() so that it gets some time to fetch the user if the app is running on a slow internet.

希望这能解决您的问题.谢谢.

I hope this solves your problem. Thank You.