Firebase: how to check if user is logged in?

I think it works like the :

FirebaseAuth.getInstance().getCurrentUser()

It should return null if a user is not logged in.


To check if user is logged in:

 private FirebaseAuth firebaseAuth;
 FirebaseAuth.AuthStateListener mAuthListener;

Then in your onCreate:

     firebaseAuth = FirebaseAuth.getInstance();

      mAuthListener = new FirebaseAuth.AuthStateListener(){
                @Override
                public  void  onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if(user!=null){
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
}
                }


            };

This can be created in an auth state class or an interface.Then you can simply call the auth state or check in whichever activity you want to check it in with:

Checking the auth state when an activity is running:

 @Override
    protected void onStart() {
        super.onStart();
        firebaseAuth.addAuthStateListener(mAuthListener);
    }


    @Override
    protected void onResume() {
        super.onResume();
        firebaseAuth.addAuthStateListener(mAuthListener);
        }




    @Override
    protected void onStop() {
        super.onStop();
        firebaseAuth.removeAuthStateListener(mAuthListener);
    }

Now about your login:After setting your boolean values to check the user is logged in state:(Default boolean set to false)

firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            progressBar.setVisibility(View.GONE);
                            if (!task.isSuccessful()) {
//set a your boolean to false
current_user_db.setValue(false);

and if user is successfully logged in,set it to true followed by your intent:

else {


String userid = firebaseAuth.getCurrentUser().getUid();
                            DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference("Users").child(userid);
                            current_user_db.setValue(true);
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();

                        }

you will then have a your node set to False if user is logged in or false if user is not successfully logged in.


I've had a similar issue and it was that signing out of Firebase is not enough - it will sign in automatically again.

It's necessary also to sign out using the GoogleSignInApi:

firebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(apiClient);