【问题标题】:Firestore get DocumentSnapshot's field's valueFirestore 获取 DocumentSnapshot 的字段值
【发布时间】:2018-07-07 15:51:12
【问题描述】:

如果我有一个 Firebase Firestore 数据库,我已经为与右侧集合对应的文档检索了一个 DocumentSnapshot 并存储在一个 document 变量中,那么我该如何检索该 DocumentSnapshot 中的值“用户名”字段?该字段有一个字符串值。

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    DocumentSnapshot 有一个方法 getString(),它接受一个字段的名称并将其值作为字符串返回。

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

    【讨论】:

    • 当我使用这段代码时,AndroidStudio 会在Incompatible types, Required: java.lang.String, found java.lang.Object 处加上红色下划线,为什么会给出一个通用对象?
    • 您可能会得到一个通用对象,因为该字段没有字符串。您可以在 Firestore 控制台中发布文档的屏幕截图吗?
    • 更新截图
    • @Paradox 使用获取字符串未获取
    【解决方案2】:

    您可以使用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的文档

    【讨论】:

    • 这是 Web9 的标准,模块化。
    【解决方案3】:

    您需要通过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 才能获取字段值。

    【讨论】:

      【解决方案4】:

      当我在 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);
      

      【讨论】:

        【解决方案5】:

        这是获取文档价值的另一种简单方法(在您的情况下):

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

        【讨论】:

        • 关键是这不是高性能的,因为你得到了整个文档,而不仅仅是所需的字段。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-24
        • 2018-03-28
        • 2018-08-02
        • 1970-01-01
        • 2020-09-10
        • 2019-03-12
        • 1970-01-01
        相关资源
        最近更新 更多