Firestore get DocumentSnapshot's field's value

后端 未结 5 640
盖世英雄少女心
盖世英雄少女心 2021-02-02 09:10

If I have a Firebase Firestore database which I have retrieved a DocumentSnapshot for the document corresponding to the collection on the right and stored in a

5条回答
  •  轮回少年
    2021-02-02 10:01

    I can only reference the field's data as Strings when I am inside the onComplete, but when I try reference it outside it. I get a nullPointerException and it crashes my activity.

    // Gets user document from Firestore as reference
        DocumentReference docRef = mFirestore.collection("users").document(userID);
    
        docRef.get().addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
    
                        Log.d(TAG, "DocumentSnapshot data: " + document.getData());
                        Log.d(TAG, "db firstName getString() is: " + document.getString("firstName"));
                        Log.d(TAG, "db lastName getString() is: " + document.getString("lastName"));
    
                        mFirstName = (String) document.getString("firstName");
                        mLastName = (String) document.getString("lastName");
                        Log.d(TAG, "String mFirstName is: " + mFirstName);
                        Log.d(TAG, "String mLastName is: " + mLastName);
    
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    
        //string checking outside the docRef.get().addOnCompleteListener code
        //commented it out because it causes a java.lang.NullPointerException: println needs a message
        //Log.v("NAME", mFirstName);
        //Log.v("NAME", mLastName);
    
        // sets the text on the TextViews
        tvFirstName = (TextView)findViewById(R.id.tvFirstName);
        tvFirstName.setText(mFirstName);
        tvLastName = (TextView)findViewById(R.id.tvLastName);
        tvLastName.setText(mLastName);
    

提交回复
热议问题