我有一个模型类Appointment
,其类型为字段, 我需要在Firestore实时数据库中监听并从其subCollection
获取所有文档 ,上传逻辑可以完美运行,但是由于这实际上是我第一次进入Firestore,因此在获取数据方面遇到了一些麻烦。
获取文档后 我需要按类型将它们分开 (约会类型A,约会类型B)
这是我到目前为止所获得的,但我似乎无法超越!
PS。以下代码主要基于Firebase文档!
@Override
public void onStart() {
super.onStart();
//get all appointments
mFirestore.collection("reporters").document(mUser.getUid()).collection("appointments")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
mFirestore.collection("reporters").document().collection("appointments")
.whereEqualTo("type", "typeB")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value,
@Nullable FirebaseFirestoreException e) {
if (e != null) {
Toast.makeText(getActivity(), "listen failed", Toast.LENGTH_SHORT).show();
return;
}
for (QueryDocumentSnapshot doc : value) {
if (doc.get("name") != null) {
v_appointmentsList.add(doc.toObject(Appointment.class));
}
}
}
});
mFirestore.collection("reporters").document().collection("appointments")
.whereEqualTo("type", "typeA")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value,
@Nullable FirebaseFirestoreException e) {
if (e != null) {
Toast.makeText(getActivity(), "listen failed", Toast.LENGTH_SHORT).show();
return;
}
for (QueryDocumentSnapshot doc : value) {
if (doc.get("name") != null) {
p_appointmentsList.add(doc.toObject(Appointment.class));
}
}
}
});
//get all docs
//....
//sort by date [max -> min || min -> max]
//...
//get index [0] || index [last]
//...
//if it is vax then affect to variables v_
//if it is ped then affect to variables p_
}
});
}
答案 0 :(得分:1)
对于您的情况,我建议您执行以下操作(我的回答基于下面的评论部分),对于类似的情况,使用实时数据库并不重要,您可以尝试使用此方法:
//colRef is a reference/path to your collection
//filter by type with .whereEqualTo("field", "type")
colRef.whereEqualTo("type", "yourType")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
//add to your arraylist
}
} else {
Toast.makeText(getContext(), "fail to get docs", Toast.LENGTH_SHORT).show();
}
}
});
//repeat the process for the second type
//if you have more types I suggest using another approach