0

User should be able to upload multiple images in one post. I tried to add all urls to a ArrayList and then to store them to firestore. All I get are errors.

"imageList" returns always null

Here is my code:

fun uploadPost(images:ArrayList<Uri>, imageCount: Int, description:String){

    images.forEach { image->
        val imageRef = storageReferenence.child(System.currentTimeMillis().toString()
                +"."+ image.lastPathSegment)
        val uploadTask = imageRef.putFile((image))
        uploadTask.addOnSuccessListener {
            val downloadUrl = imageRef.downloadUrl
            downloadUrl.addOnSuccessListener {uri->
                Log.d("IMAGES", uri.toString())
                imageList!!.add(uri.toString())

                count++
            }
        }

    }



    //firebaseRepository.firestoreDB.collection("post").document(firebaseRepository.userid.toString()).update(post)
}

enter image description here

You can see that the Log has the url but when I try to add it to the imageList it fails to do so.

THIS CAUSES THE ERROR: imageList!!.add(uri.toString()) ERROR MSG: AddViewModel$uploadPost$$inlined$forEach$lambda$1$1.onSuccess

I don`t really know what is better to store the images as an array or to store each image like this: image1:url... , image2: url.. I need them to be part of the same document.

  • At which particular line of code does the error occur? – Alex Mamo Sep 15 '20 at 13:05
  • imageList!!.add(uri.toString()) ERROR: AddViewModel$uploadPost$$inlined$forEach$lambda$1$1.onSuccess – Marijan Klarić Sep 15 '20 at 13:18
  • 1
    Any code that needs the download URL needs to be inside the `onSuccessListener` callback. By the time you now try to use write `imageList ` to Firestore, the `imageList!!.add(uri.toString())` line hasn't run yet. See https://stackoverflow.com/questions/62699565/how-to-get-download-url-for-firebase-storage-and-update-firestore-document/62699990#62699990 – Frank van Puffelen Sep 15 '20 at 14:00
  • Log.d("IMAGES", uri.toString()) i get a url here but when I retrieve from the imageList nothing happens it returns null – Marijan Klarić Sep 15 '20 at 17:25
  • I see a kotlinnullpointerexcception. Maybe this link can help you: https://stackoverflow.com/questions/50716294/kotlin-why-do-i-get-a-kotlinnullpointerexception – MrTech Sep 15 '20 at 19:31
  • 1
    @Frank: Good pointer for the client. Why not post it as an answer? – MrTech Sep 15 '20 at 21:38
  • Do you have a loop? I see count ++ in the code you provided and I do not see the context. – MrTech Sep 16 '20 at 17:24

0 Answers0