Skip to content Skip to sidebar Skip to footer

App Crashes With Java.lang.nullpointerexception

I wanted to filter all the posts with orderbychild. But the app crashes. After I debug it shows error on : final String currentUserId=mAuth.getCurrentUser().getUid(); this line of

Solution 1:

The problem is that in firebase when you create a user it doesn't sign in the user.

First check mAuth is null or not then get getUid if not null.

FirebaseUseruser= FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in// Get User details 

} else {
    // No user is signed in// create new signin 
}

Solution 2:

The problem is that you're synchronously reading the current user, which may return null:

finalString currentUserId=mAuth.getCurrentUser().getUid()

When the app starts, the sign-in state of the user may not be known yet. In that case getCurrentUser() will return null, which crashes your code.

To prevent this, you should listen for the authentication state to be confirmed/changed:

FirebaseAuth.getInstance().addAuthStateListener(newFirebaseAuth.AuthStateListener() {
    @OverridepublicvoidonAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUseruser= firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        }
    }
});

Post a Comment for "App Crashes With Java.lang.nullpointerexception"