Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27237

FirebaseAuth.AuthStateListener not called in Fragment class

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?

Upvotes: 1

Views: 3243

Answers (2)

Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27237

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

@Override
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);
    }
}

Upvotes: 5

Power team
Power team

Reputation: 1

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser name = firebaseAuth.getCurrentUser();
            if (name != null) {
                finish();
                startActivity(new Intent(getApplicationContext(), Subscriber.class));
            }
        }
    };
    mAuth.addAuthStateListener(mAuthListener);

Upvotes: 0

Related Questions