'How to solve Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.signOut()' on a null object reference?

I have two activities (mainactivity and main2activity). I got the Google login code from GitHub Firebase login demo. When in SignIn with Google, it redirects to second activity which is the navigation drawer activity, in the drawer, I placed SignOut where it gives me error:

Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.signOut()' on a null object reference

SignOut method in mainactivity is

public void signOut() {
    // Firebase sign out
    mAuth.signOut();
    LoginManager.getInstance().logOut();
    // Google sign out
    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    updateUI(null);
                }
            });
}

This is how I called the method:

MainActivity ma = new MainActivity();
ma.signOut();

How to SignOut from drawer?



Solution 1:[1]

Never use new to create an Activity. Activities should only be created by the framework. You should have an instance of the signin from when you loggedin, use that.

Solution 2:[2]

It's Late but some guys will found it helpful . In Your MainAcivity.

Add this line of code.

FirebaseAuth mAuth = FirebaseAuth.getInstance();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabe Sechan
Solution 2 Dharmik A Viv