有没有办法从子集合中获取数据?下面是我的数据库的结构,对于每个用户,将在“ userinfo”子集合中仅创建一个文档来仅存储用户名和电子邮件。
我正在尝试从Firestore获取“用户名”和“电子邮件”值,然后将这些值设置为字符串,例如:
字符串用户名=? 字符串电子邮件=?
"main"(root_collection)
|
|=>userid1(auto-generated)
|
|=>"userinfo"(sub-collection)=>documentID(auto)=>username: mary
| =>email:mary@gmail.com
|
|
|=>"emotions"(sub-collection)=>documentID(auto)=>happy: true
=>sad:false
=>depressed:false
我从其他问题中读取了其他一些答案,说可以使用
检索字段值String value = documentSnapshot.getString("field");
但是我仍然不知道该怎么做?我写了一些东西,我不知道如何获得价值。
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference userRef = db.collection("main").document(userId).collection("userinfo");
userRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
//get the value
String value = queryDocumentSnapshots.getDocuments("username"); // how ??
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
也有一个对象类UserInfo
import java.io.Serializable;
public class UserInfo implements Serializable {
private String email, username;
public UserInfo() {}
public UserInfo(String email, String username) {
this.email = email;
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
请帮助,非常感谢。
答案 0 :(得分:2)
有没有办法从子集合中获取数据?
是的,有。要获取该数据,您必须按照以下代码行遍历结果:
userRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String value = document.getString("username");
Log.d("TAG", value);
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
logcat中的结果将是:
mary