Firebase getCurrentUser is returning null in new android activity

后端 未结 1 1227
自闭症患者
自闭症患者 2020-12-06 08:18

LoginActivity:

private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

@Override
protected void onCreate(Bundle savedInstan         


        
相关标签:
1条回答
  • 2020-12-06 08:55

    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.

    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\n"+mUserId,Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(ListActivity.this, "no id got", Toast.LENGTH_SHORT).show();
                }
    
            }
        };
    

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

    onResume()

     mCurrentUser = mAuth.getCurrentUser();
    

    in case of slow connection

    mCurrentUser = user;
    

    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.

    0 讨论(0)
提交回复
热议问题