I’m trying to create a custom object from a document in the Firebase Firestore. Whenever I try to use the User object, I get a NullPointerException on the user object:
static FirebaseAuth fAuth = FirebaseAuth.getInstance(); static FirebaseFirestore fStore = FirebaseFirestore.getInstance(); static User user; public static void getUserFromFirebaseUser() { DocumentReference docRef = fStore.collection("users").document(fAuth.getCurrentUser().getUid()); docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { user = task.getResult().toObject(User.class); Log.d("STACKOVERFLOW", "user created"); System.out.println("Success : " + user.getShortEmail()); } else {Log.d("STACKOVERFLOW", "user not created");} } }); }
I call getUserFromFirebaseUser here:
public static void updateFirestoreDatabase(// my data) { Log.d("STACKOVERFLOW", "before getUserFromFirebaseUser() call"); getUserFromFirebaseUser(); Log.d("STACKOVERFLOW", "after getUserFromFirebaseUser() call"); System.out.print(user.getShortEmail()); // This errors out. // update Firestore ... }
Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.bertcooperlab.sam51.User.getShortEmail()' on a null object reference
Here is the User class:
public class User { private String shortEmail; private int companyNumber; public User () {} public User (String email, int companyNumber) { this.shortEmail = email.substring(0, email.indexOf('@')); this.companyNumber = companyNumber; } public String getShortEmail() { return shortEmail; } public int getCompanyNumber() { return companyNumber; } }
I’m relatively new to using Firebase with Android. Any help is appreciated.
EDIT I’ve added Log statements to the onComplete() method and surrounding the getUserFromFirebaseUser() call in updateFirestoreDatabase().
D/STACKOVERFLOW: before getUserFromFirebaseUser() call D/STACKOVERFLOW: after getUserFromFirebaseUser() call D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: com.bertcooperlab.sam51, PID: 3521 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.bertcooperlab.sam51.User.getShortEmail()' on a null object reference
So, I think the onCompleteListener is not able to finish
Advertisement
Answer
You are trying to use user.getShortEmail()
while user
is null. That’s because user
hasn’t yet been assigned a value. This is becasue docRef.get().addOnCompleteListener()
is asynchronous and returns immediately, before the query is complete. If you put logs around and inside the callback, it will become more clear in what order things are actually happening.
You’re probably going to have to take up some form of asynchronous programming. In modern android, that’s going to be Kotlin coroutines or LiveData, and your code will look very little like it does now.