'downloadUrl give empty result

I have a function to upload some data to firebase like this

private fun addDatatoFirebase(){
    val addImage = StorageRef.child(preferences.getValue("username").toString()).child("food_pics/"+UUID.randomUUID())
    addImage.putFile(FilePath).addOnSuccessListener {
        addImage.downloadUrl.addOnSuccessListener {
            PicUrl = it.toString()
        }
    }


    val dataRef = ref.child(preferences.getValue("username").toString()).child("FoodList/"+UUID.randomUUID().toString())
        dataRef.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                id = snapshot.ref
                Log.w("PicUrl data",PicUrl)
                dataRef.child("image_pic").setValue(PicUrl)
                dataRef.child("name").setValue(food_name)
                dataRef.child("avail").setValue(availability)
                dataRef.child("price").setValue(food_price.toInt())
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)                }

        })
}

It has a problem that PicUrl is empty eventhough i already give it value here :

addImage.downloadUrl.addOnSuccessListener {
                PicUrl = it.toString()
            }

The log shows that PicUrl Value is "", since i initialize the var with PicUrl = "" here is the log :

W/PicUrl data: 
W/PicUrl data: 

So now, i wonder what is wrong with my code in that function that create such error



Solution 1:[1]

I found the answer

addImage.downloadUrl.addOnSuccessListener {
                PicUrl = it.toString()
                dataRef.child("image_pic").setValue(PicUrl)
            }

Since downloadUrl is asynchronous. I need to include the code that need the value of it inside the callback which means putting :

dataRef.child("image_pic").setValue(PicUrl)

inside addOnSuccessListener

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MadsterMIZE