Search code examples
androidfirebaseloopsasynchronousandroid-asynctask

Async task could not keep up with for loop (firebase)


  for (Uri mUri : mSelected) 
   {
       imagesRef = storageRef.child(postid + mUri.getLastPathSegment());
       imagesRef.putFile(mUri).addOnSuccessListener(task4 ->
       db.collection("posts").document(postid).update("photo_id", FieldValue.arrayUnion(imagesRef.getDownloadUrl())));
   }

So, now i am working with firestore and firebase storage. I uploaded (multiple) images to the storage, and when it is uploaded, i get the download url and wants to add it into my firestore. So, the problem is, only the last image is added into firestore, all images are added into storage, but only the last imgUrl is added into firestore. Since firebase uses async tasks i suspect it is because the update task could not keep up with the loop. Any help is very much appreciated !!!


Solution

  • I think the problem might be with imagesRef, it is declared outside of for (Uri mUri : mSelected) {...} and therefore it is being replaced before addOnSuccessListener(...) responds.

    So, declare it locally to for (Uri mUri : mSelected) {...} and see if it will not resolve the issue. Like this

    for (Uri mUri : mSelected) 
    {
           var imagesRef = storageRef.child(postid + mUri.getLastPathSegment());
           imagesRef.putFile(mUri).addOnSuccessListener(task4 ->
           db.collection("posts").document(postid).update("photo_id", FieldValue.arrayUnion(imagesRef.getDownloadUrl())));
     }