问题
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