如果我有一个Firebase Firestore数据库,我已经为与右边的集合对应的文档检索了DocumentSnapshot
并存储在document
变量中,那么我该如何检索该值DocumentSnapshot
在该字段"用户名"?该字段具有字符串值。
答案 0 :(得分:14)
DocumentSnapshot有一个方法getString(),它取一个字段的名称并将其值作为字符串返回。
String value = document.getString("username");
答案 1 :(得分: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才能获得字段值。
答案 2 :(得分: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
的文档
答案 3 :(得分:0)
当我在onComplete内部时,我只能以Strings形式引用该字段的数据,但是当我尝试在它外部时引用它时。我收到一个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);
答案 4 :(得分:0)
这里是获取文档价值的另一种简单方法(针对您的情况):
Firestore.instance
.collection('users').document('xsajAansjdna')
.get()
.then((value) =>
print("Fetched ==>>>"+value.data["username"]));