Firestore获取DocumentSnapshot的字段值

问题描述 投票:6回答:3

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

enter image description here

android firebase google-cloud-firestore
3个回答
14
投票

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

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

2
投票

你需要做一个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以获取字段值。


0
投票

你可以使用get方法来获得一个字段的值

String username = (String) docuemnt.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的文档

© www.soinside.com 2019 - 2024. All rights reserved.