这是我的数据结构:
我正在尝试获取allergyId1和allergyId2的值。有什么方法可以分别获取“过敏原”和“描述”的值吗?我想将这些值分配给另一个名为Allergy的类,并将它们添加到ArrayList中。例如:
Allergy allergy = new Allergy();
ArrayList<Allergy> allergies = new ArrayList<>();
// Data of "allergyId1"
allergy.setAllergen(the value of allergen);
allergy.setDescription(the value of description);
allergies.add(allergy);
我试图将返回的对象转换为Json对象,但是我认为必须有一种更有效的方法来从Firestore获取数据。
private void retrieveAllergiesData() {
FirebaseUser user = mAuth.getCurrentUser();
DocumentReference ref = db.collection(user.getUid()).document("allergies");
ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> tmp = new HashMap<>();
tmp = document.getData();
for (Map.Entry<String, Object> entry : tmp.entrySet()) {
Log.d("allergy", entry.getKey() + ":" + entry.getValue().toString());
}
} else {
Log.d("fb", "No such document");
}
} else {
Log.d("fb", "get failed with ", task.getException());
}
}
});
}
这就是我得到的
答案 0 :(得分:0)
这就是它的工作方式。就性能而言,它没有比处理文档中返回的Map更为有效的方法。
尽管如此,您不必使用它就不必创建新地图:
Map<String, Object> tmp = new HashMap<>();
tmp = document.getData();
可以这样简化:
Map<String, Object> tmp = document.getData();
答案 1 :(得分:0)
使用构造函数和Allergy
get
set
private class Allergy {
private String allergen;
private String description;
public Allergies() {
}
public Allergies(String allergen, String description) {
this.allergen = allergen;
this.description = description;
}
public String getAllergen() {
return allergen;
}
public void setAllergen(String allergen) {
this.allergen = allergen;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
然后将Object
替换为Allergy
。这可能适合您的情况。
private void retrieveAllergiesData() {
FirebaseUser user = mAuth.getCurrentUser();
DocumentReference ref = db.collection(user.getUid()).document("allergies");
ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Allergy> tmp = new HashMap<>();
tmp = document.getData();
for (Map.Entry<String, Allergy> entry : tmp.entrySet()) {
String allergen = entry.getValue().getAllergen();
String description = entry.getValue().getDescription();
}
} else {
Log.d("fb", "No such document");
}
} else {
Log.d("fb", "get failed with ", task.getException());
}
}
});
}