根据文档列表查询FireStore [英] Query FireStore against a List of Documents
问题描述
我有一个 List< String>
,其名称引用了我想从FireStore中检索的文档.我想在内容加载完成后访问其中的内容,因此我在使用数据的 Fragment
中实现了 OnCompleteListener
.但是,我不确定如何在 Task
中运行循环以查询FireStore的每个文档.我在Repository类中查询FireStore,该类通过我的 ViewModel
返回一个 Task
对象,最后返回到我的 Fragment
.我希望存储库返回一个 Task
,以便可以将 OnCompleteListener
附加到它,以便知道何时完成数据加载.
I have a List<String>
of names referring to Documents that I want to retrieve from FireStore. I want to access the contents after they are finished loading so I have implemented an OnCompleteListener
in the Fragment
that uses the data. However, I am not sure how to run a loop within a Task
to query FireStore for each Document. I am querying FireStore in a Repository class that returns a Task
object back through my ViewModel
and finally to my Fragment
. I want the Repository to return a Task
so that I can attach an OnCompleteListener
to it in order to know when I have finished loading my data.
我的存储库 Query
方法:
public Task<List<GroupBase>> getGroups(List<String> myGroupTags){
final List<GroupBase> myGroups = new ArrayList<>();
for(String groupTag : myGroupTags){
groupCollection.document(groupTag).get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
myGroups.add(task.getResult().toObject(GroupBase.class));
}
}
});
}
return null; //Ignore this for now.
}
我知道这不会返回我需要的东西,但是我不确定如何构造在其中包含循环的 Task
.我是否需要在我的 Fragment
中提取 List< String>
的内容,并对每个项目运行单独的查询?
I know this won't return what I need but I am not sure how to structure a Task
that incorporates a loop inside of it. Would I need to extract the contents of the List<String>
in my Fragment
and run individual queries for each item?
任何建议将不胜感激.
推荐答案
根据您的评论:
我有一个文档名称列表,我需要将其转换为实质上是一个任务列表,以检索整个文档.
I have a List of Document names and I need to transform this to essentially a List of Tasks to retrieve the entire document.
要解决此问题,请使用以下代码行:
To solve this, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference collRef = rootRef.collection("yourCollection");
List<String> myGroupTags = new ArrayList<>();
List<DocumentReference> listDocRef = new ArrayList<>();
for(String s : myGroupTags) {
DocumentReference docRef = collRef.document(s);
listDocRef.add(docRef);
}
List<Task<DocumentSnapshot>> tasks = new ArrayList<>();
for (DocumentReference documentReference : listDocRef) {
Task<DocumentSnapshot> documentSnapshotTask = documentReference.get();
tasks.add(documentSnapshotTask);
}
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
@Override
public void onSuccess(List<Object> list) {
//Do what you need to do with your list
for (Object object : list) {
GroupBase gb = ((DocumentSnapshot) object).toObject(GroupBase.class);
Log.d("TAG", tp.getPropertyname);
}
}
});
这篇关于根据文档列表查询FireStore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!