Query FireStore against a List of Documents

隐身守侯 提交于 2019-12-24 00:46:13

问题


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.

My Repository Query method:

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.
}

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?

Any suggestions would be greatly appreciated.


回答1:


According to your comment:

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);
        }
    }
});


来源:https://stackoverflow.com/questions/54482809/query-firestore-against-a-list-of-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!