FirebaseAuth.AuthStateListener not called in Fragment class

我的未来我决定 提交于 2019-12-24 07:58:03

问题


My navigation drawer contained in MainActivity navigates to several Fragments. In the onCreate method of these Fragment classes, am trying to onAuthStateChanged to get the current user:

FirebaseAuth.AuthStateListener mAuthListener;
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            user = firebaseAuth.getCurrentUser();
            if (user != null ) {
                Log.e(TAG, "onAuthStateChanged:signed_in" + user.getUid());

            } else { //user is not logged in

                Log.e(TAG, "onAuthStateChanged:signed_out");

            }

        }
    };
   }

but onAuthStateChanged is never called. Similar code in MainActivity works just fine. I have tried calling this code in the onCreateView() and onResume() methods of the Fragment but nothing happens. To solve this and get the current user, I created a method in the MainActivity:

 public FirebaseUser getFirebaseUser() {
    return user;
 }

and then called the method in the Fragment class by doing:

FirebaseUser user = ((MainActivity) getActivity()).getFirebaseUser();

if (user != null ) {
            Log.e(TAG, "onAuthStateChanged:signed_in" + user.getUid());

        } else { //user is not logged in

            Log.e(TAG, "onAuthStateChanged:signed_out");

        }

and everything works just fine. My question is, why can't I call

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
      ...

from my Fragment classes?


回答1:


Thanks to @ArnisShaykh, I discovered I wasn't calling:

public void onStart(){
    super.onStart();
    firebaseAuth.addAuthStateListener(mAuthListener); //firebaseAuth is of class FirebaseAuth
}

In the Fragment class.

remember to also add:

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        firebaseAuth.removeAuthStateListener(mAuthListener);
    }
}


来源:https://stackoverflow.com/questions/41562916/firebaseauth-authstatelistener-not-called-in-fragment-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!