3
votes

I am using both Firebase Authentification and Firestore for my Android app. What I am trying to do is the following:

  • the user signs in
  • if it's the first time the user signs in a document named by his uid is created
  • if the user has already signed in before (hence document named by uid already exists) then I load some further data.

Here's my logic to solve this:

  • get the FirebaseUser from FirebaseAuth instance
  • from the FirebaseUser I get the uid
  • build a DocumentReference with this uid
  • use get() query on the DocumentReference
  • if DocumentSnapshot is != null then user already exists in firestore
  • if DocumentSnapshot == null the user doesn't exist and I create it in firestore

I was testing the code below:

    FirebaseUser user = mAuth.getCurrentUser();
    if(user != null) {
        // get uid from user
        String uid = user.getUid();

        // make a query to firestore db for uid
        DocumentReference userDoc = db.collection("users").document(uid);
        userDoc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null) {
                        Log.d(LOG_TAG, "DocumentSnapshot data: " + task.getResult().getData());
                    } else {
                        Log.d(LOG_TAG, "No such document");
                    }
                } else {
                    Log.d(LOG_TAG, "get failed with ", task.getException());
                }
            }
        });
    }

When uid exists in firestore I get the log message with appropriate data but when it doesn't I get the following exception and I can't find a way to get to use DocumentSnapshot.exists():

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

Can anyone help me understand what I am doing wrong ?

Thanks a million ! :)

1

1 Answers

3
votes

The object returned by get() is a DocumentSnapshot not the document itself. The DocumentSnapshot is never null. Use the exists() method to determine if the snapshot contains a document. If exists() is true, you can safely use one of the getXXX() methods (in your case, getData() for a map) to obtain the value of the document.

@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
    if (task.isSuccessful()) {
        DocumentSnapshot snapshot = task.getResult();
        if (snapshot.exists()) {
            Log.d(LOG_TAG, "DocumentSnapshot data: " + snapshot.getData());
        } else {
            Log.d(LOG_TAG, "No such document");
        }
    } else {
        Log.d(LOG_TAG, "get failed with ", task.getException());
    }
}