如果我有一个Firebase Firestore数据库,我已经为与右边的集合对应的文档检索了DocumentSnapshot
并存储在document
变量中,那么我如何在“用户名”字段中检索该DocumentSnapshot
中的值?该字段具有字符串值。
DocumentSnapshot有一个方法getString(),它取一个字段的名称并将其值作为String返回。
String value = document.getString("username");
你需要做一个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以获取字段值。
你可以使用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
的文档