簡體   English   中英

Firestore 獲取 DocumentSnapshot 字段的值

[英]Firestore get DocumentSnapshot's field's value

如果我有一個 Firebase Firestore 數據庫,我檢索了與右側集合對應的文檔的DocumentSnapshot並存儲在document變量中,那么我如何檢索該DocumentSnapshot中“用戶名”字段的值? 該字段有一個字符串值。

在此處輸入圖像描述

DocumentSnapshot有一個getString()方法,它接受字段的名稱並將其值作為字符串返回。

String value = document.getString("username");

您可以使用get方法獲取字段的值

String username = (String) document.get("username");  //if the field is String
Boolean b = (Boolean) document.get("isPublic");       //if the field is Boolean
Integer i = (Integer) document.get("age")             //if the field is Integer

查看DocumentSnapshot

您需要執行DocumentReference才能獲取DocumentReference中的內容。

一個簡單的會是這樣的。

DocumentReference docRef = myDB.collection("users").document("username");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
     public void onComplete(@NonNull Task<DocumentSnapshot> task) {
          if (task.isSuccessful()) {
               DocumentSnapshot document = task.getResult();
                    if (document != null) {
                         Log.i("LOGGER","First "+document.getString("first"));
                         Log.i("LOGGER","Last "+document.getString("last"));
                         Log.i("LOGGER","Born "+document.getString("born"));
                    } else {
                         Log.d("LOGGER", "No such document");
                    }
               } else {
                    Log.d("LOGGER", "get failed with ", task.getException());
                }
          }
     });

缺點是您需要知道您的文檔 ID 才能獲取字段值。

當我在 onComplete 內部時,我只能將字段的數據作為字符串引用,但是當我嘗試在它外部引用它時。 我得到一個 nullPointerException 並且它使我的活動崩潰。

// Gets user document from Firestore as reference
    DocumentReference docRef = mFirestore.collection("users").document(userID);

    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> 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);

這是獲取文檔值的另一種簡單方法(在您的情況下):

Firestore.instance
.collection('users').document('xsajAansjdna')
.get()
.then((value) =>
print("Fetched ==>>>"+value.data["username"]));
`Firestore.instance
.collection('users').document('xsajAansjdna')
.get()
.then((value) =>
print("Fetched ==>>>"+value.data()["username"]));`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM