Reputation: 461
I am new to java
. I have a firestore_member_list
. In firestore_member_list, it contains values: ["steve","ram","kam"]
. I am using for
loop to pass values one by one.
loadingbar.show()
for( int k=0; k<firestore_member_list.size();k++){
String member_name = firestore_member_list.get(k);
final DocumentReference memDataNameCol = firestoredb.collection("member_collection").document(member_name);
memDataNameCol.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
// In here, I am retreiveing the document data from firestore and assigning it to the ArrayList which is `all_mem_data`
all_mem_data.add(document.get("member_name").toString());
all_mem_data.add(document.get("member_address").toString());
Toast.makeText(getActivity(), "all mem data array"+all_mem_data.toString(),
Toast.LENGTH_LONG).show();
}
}
}
});
}
Log.d("all_mem_data",all_mem_data)
loadingbar.hide()
I know firestore executes asynchronously. Since firestore retrieves data asynchronous, before filling the array of all_mem_data
, the last line gets executed and shows the empty array. How to wait for the array to get filled and after filling,execute the last two lines. Please help me with solutions.
Upvotes: 0
Views: 622
Reputation: 598807
Any code that needs the data from the database, needs to be inside the onComplete
that fires when that data is available.
If you want to wait until all documents are loaded, you can for example keep a counter:
loadingbar.show()
int completeCount = 0;
for( int k=0; k<firestore_member_list.size();k++){
String member_name = firestore_member_list.get(k);
final DocumentReference memDataNameCol = firestoredb.collection("member_collection").document(member_name);
memDataNameCol.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
...
if (completeCount++ == firestore_member_list.size()-1) {
Log.d("all_mem_data",all_mem_data)
loadingbar.hide()
}
}
});
}
Upvotes: 1