Home > Software engineering >  I'm uploading multiple images to Firebase and it's completed, but I can't save the ur
I'm uploading multiple images to Firebase and it's completed, but I can't save the ur

Time:10-30

I'm uploading multiple images to Firebase and it's completed, but I can't save the URL link to a list.

private fun uploadAllImage(imageList: MutableList<Uri>) {
    val storageReference = FirebaseStorage.getInstance().reference.child("image")
    val storeImage = mutableListOf<Uri>()

    for (i in imageList) {

        val indImg = i
        var imageName = storageReference.child("Image"   indImg.lastPathSegment)

        imageName.putFile(indImg).addOnSuccessListener {
            binding.userImage.setImageURI(null)
            imageName.downloadUrl.addOnSuccessListener {
                Log.d("image", it.toString())
                storeImage.add(it)
            }
        }
    }

    Log.d("imageList", storeImage.size.toString())
}

CodePudding user response:

try out on complete listener callback like this

imageName.putFile(indImg).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val downloadUrl = task.result.toString()
    }
}

CodePudding user response:

When you are calling the .putFile() method, it means that you are performing an asynchronous operation. Remember, that it takes time to actually upload a file to Firebase Storage. So any code that needs to process data related to that operation, needs to be added inside the onSuccess() method, or be called from there. So you have to move the following line of code:

Log.d("imageList", storeImage.size.toString())

Inside the callback, to actually know when a single upload is complete.

However, when you add multiple files in parallel, you'll never know when all uploads are completed, unless you perform an upload operation right after another. This can be done using a recursion (a function that invokes itself). So please try to use my answer from the following post:

It's Java code but can be really simple converted into Kotlin.

  • Related