Guy Ohm
Guy Ohm

Reputation: 89

Querying Firestore for uid document after authentification => IllegalStateException

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

Here's my logic to solve this:

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 ! :)

Upvotes: 3

Views: 1042

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38299

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());
    }
}

Upvotes: 3

Related Questions