'Application crashing when user signs out [duplicate]

Guys i have been making this simple Uber app and whenever the Driver LogsOut my app crashes because the getCurrentUser() method is returning a null value. But whenever the user logsOut im closing the activity, and before calling getCurrentUser() i have this if(getApplicationContext()!=null) which should return false because the activity is closed so it should prevent getCurrentUser() from being called. How do i prevent it from crashing? What am i missing here?

This is where on Button click i logOut my user

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//some code here

    mLogout=(Button)findViewById(R.id.logout);
            mLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    isLoggingOut = true;
                    disconnectDriver();
                    
                    //Signing out user here
                    FirebaseAuth.getInstance().signOut();
                    Intent intent = new Intent(DriverMapActivity.this, MainActivity.class);
                    startActivity(intent);
                    return;
                }
            });
//some code here
}

This is where the error is happening

@Override
    //this is going to run whenever the driver location changes
    public void onLocationChanged(Location location) {
        if(getApplicationContext()!=null) {

            mLastLocation = location;
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
          
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

            //
            //This is where the error is happening
            //java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
            
            String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
            
            DatabaseReference refAvailable = FirebaseDatabase.getInstance().getReference("driversAvailable");
            
            DatabaseReference refWorking  = FirebaseDatabase.getInstance().getReference("driversWorking");
            
            GeoFire geoFireAvailable = new GeoFire(refAvailable);
           
            GeoFire geoFireWorking = new GeoFire(refWorking);
      
            switch(customerId){
               
                case "":

                   geoFireWorking.removeLocation(userId);
                    geoFireAvailable.setLocation(userId, new GeoLocation(location.getLatitude(), location.getLongitude()));
                    break;
                default:

                   
                    geoFireAvailable.removeLocation(userId);
                    geoFireWorking.setLocation(userId, new GeoLocation(location.getLatitude(), location.getLongitude()));
                    break;

            }
        }
    }

This is the Error Log

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.jonanako.uber, PID: 15522
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.jonanako.uber.DriverMapActivity.onLocationChanged(DriverMapActivity.java:211)
        at com.google.android.gms.internal.location.zzat.notifyListener(com.google.android.gms:play-services-location@@18.0.0:2)
        at com.google.android.gms.common.api.internal.ListenerHolder.zaa(com.google.android.gms:play-services-base@@18.0.1:2)
        at com.google.android.gms.common.api.internal.zacb.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)


Solution 1:[1]

getApplicationContext() won't be null when you finish() Activity, even last or one and only. consider using if(!isFinishing()), lifecycle checking or just set own boolean flag.

additionally you may (should) also check that getCurrentUser() returns null, that would mean that user logs out. if is null then don't call any method on returned object (because nothing is returned in fact)

if(!isFinishing() && FirebaseAuth.getInstance().getCurrentUser()!=null) {

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 snachmsm