0

FirebaseAuth.getCurrentUser() is returning null value. Previously my code worked fine but since couple of days its returning currentUser as null.

Also I've tried my app on another device and in that device everything is working fine with the same code.

mAuth=FirebaseAuth.getInstance();
mCurrentUser=mAuth.getCurrentUser()
mUserDatabase=FirebaseDatabase.getInstance().getReference().child("Users")
                              .child(mCurrentUser.getUid());

Exception:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

I have already tried erasing app data and uninstalling and reinstalling my app on my device but nothing worked.

Is there a problem with my device or Firebase?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Juzer
  • 35
  • 1
  • 3
  • 15
  • Can you go to your Firebase Users Table and confirm that you have that user? Also, are you doing this after signing in? – Yahya Jun 24 '18 at 17:22
  • yes user already exists. i've checked it there, as i have said everything is working fine in another device – Juzer Jun 24 '18 at 17:24
  • 1
    You have to sign in first before trying to get the user! The problem seems to be that your user is not yet signed in!! – Yahya Jun 24 '18 at 17:27
  • How do I sign in when my app is crashing in the first place. – Juzer Jun 24 '18 at 17:30
  • You seem you have a lack in understanding the basic concept of how to use `Firebase` Database. You should read more about [docs](https://firebase.google.com/docs/auth/android/start/) – Yahya Jun 24 '18 at 17:33
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Yahya Jun 24 '18 at 17:35

1 Answers1

2

It looks like the user isn't signed into your app, which causes mCurrentUser.getUid() to throw an exception.

The solution is to only call getUid() is there is a signed-in yser:

mCurrentUser=mAuth.getCurrentUser();
if (mCurrentUser != null) {
    mUserDatabase=FirebaseDatabase.getInstance().getReference().child("Users")
                          .child(mCurrentUser.getUid());
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807