1
  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 !!!

Dulaj Kulathunga
  • 1,248
  • 2
  • 9
  • 19
  • 1
    just to check, does the problem is occur when you upload just 2 images at the same time? – Tsepo Nkalai Nov 18 '19 at 09:37
  • 1
    What's the value of `postid` at every iteration? – Alex Mamo Nov 18 '19 at 09:42
  • @nada yes, when i post only 1 pic the pic will get uploaded successfully , but when i upload 2 or more, only the last pic get uploaded into firestore – aishaaishapeng Nov 18 '19 at 10:21
  • @AlexMamo postid is created differently everytime, this code is used when i create a new post, thus when a user click "post", i want to upload the pictures to storage and get their url, unfortunately i am only able to upload the last url into firestore – aishaaishapeng Nov 18 '19 at 10:29

1 Answers1

1

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())));
 }
Tsepo Nkalai
  • 1,492
  • 11
  • 18
  • i tried but it just throws java.lang.reflect.InvocationTargetException error. do u perhaps know wht this means – aishaaishapeng Nov 18 '19 at 13:50
  • @aishaaishapeng did you change anything else in your code? When you remove the var does it still show the error? And to what line exactly does it point you to? – Tsepo Nkalai Nov 18 '19 at 13:59
  • thnks man! it works the error was for smtg else. to get the download url i hv to get it on success listener. Youve been great help! – aishaaishapeng Nov 18 '19 at 14:14