Martynas Krupskis
Martynas Krupskis

Reputation: 65

.getCurrentUser() never returns null - firebase

I am creating authentication with facebook for my application and everything is working fine except that when I am signed out of facebook it still passes me to the main menu of the application. Which I assume means that .getCurrentUser() does not return null even if I am signed out.

I've tried commenting out updateUI(); in my code below and that seems to fix the problem, however I would like for this code to work properly

    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser != null) {
       updateUI();
    }

Upvotes: 1

Views: 621

Answers (2)

Yash
Yash

Reputation: 3576

Try using AuthStateListener, sample:

//Declaration and defination
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        if (firebaseAuth.getCurrentUser() != null){
            //Do anything here which needs to be done after user is set is complete
            updateUI();
        }
        else {
        }
    }
};

//Init and attach
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.addAuthStateListener(authStateListener);

Upvotes: 0

sasy solutions
sasy solutions

Reputation: 179

You need to attach an authstate listener.

"There are some cases where getCurrentUser will return a non-null FirebaseUser but the underlying token is not valid. This can happen, for example, if the user was deleted on another device and the local token has not refreshed. In this case, you may get a valid user getCurrentUser but subsequent calls to authenticated resources will fail.

getCurrentUser might also return null because the auth object has not finished initializing.

If you attach an AuthStateListener you will get a callback every time the underlying token state changes. This can be useful to react to edge cases like those mentioned above." https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

https://firebase.google.com/docs/auth/android/manage-users

Upvotes: 1

Related Questions