Running Firebase get() in a loop in android

橙三吉。 提交于 2021-01-29 12:51:43

问题


I am working on an android project and have encountered a problem in getting firebase firestore documents in a loop.

//getting the document snapshot out of the uIds
                        for (int i = 0; i < uidS.size(); i++) {

                            db.collection("items")
                                    .document(uidS.get(i))
                                    .get()
                                    .addOnCompleteListener(task1 -> {

                                        if (task1.isSuccessful()) {
                                            documentSnapshots.add(task1.getResult());

                                            if (documentSnapshots.size() == uidS.size()) {
                                                //Do something here...
                                            }

                                        } else {
                                            Toast.makeText(this, "Error!!", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                        }  

Here I have a uidS arraylist which contains all the id for getting the documentSnapshot from Firestore which then are added to a documentSnapshots arraylist.

Now the problem is that the loop finishes off before the firestore task is even started which makes the order of the loop's index in Task be kind of random, like:

Loop Index:0
Loop Index:1
Loop Index:2
Loop Index:3
Beyond the loop....
In firebase task with index 0 
In firebase task with index 2 
In firebase task with index 1  
In firebase task with index 3  

I know it is the usual asynchronous behaviour of Firestore but I do not have any other way to structure the database or do anything else. How can i achieve this?

Although, I know blocking the main thread may result in ANR but I have already checked for the internet connection speed in my code so all the documentSnapshots would take less than 2 seconds.

Is there any way I can make the task be executed first then beyond the loop... or any way to just make the order of index in Task be in order and not random?

Any help would be so much appreciated :-)


回答1:


Okay so a solution for people, having the same kind of situation; would be using another data structure which does not depends upon the order of adding of elements.

I used a Hashmap<String, DocumentSnapshot> to do the job with the string being the UID.

So, in whatever order they are added, we get the DocumentSnaphot by their respective UID, further.



来源:https://stackoverflow.com/questions/63995951/running-firebase-get-in-a-loop-in-android

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