0
votes

I'm trying to get the downloadUrl of the image that I upload to the Firebase Storage. Here is the code:

val ref = FirebaseStorage.getInstance().getReference("images/$fileName")


        ref.putFile(selectedPhotoUri!!)
            .addOnSuccessListener {
                Log.d("RegisterActivity","Successfully uploaded the image: ${it.metadata?.path}")
            }
            .addOnFailureListener {
                Log.d("RegisterActivity", "Failed to upload image: ${it.message}")
            }

        ref.downloadUrl.addOnSuccessListener {
            Log.d("RegisterActivity","File location: $it")
            saveUserToFirebaseDatabase(it.toString())
        }
        ref.downloadUrl.addOnFailureListener {
            Log.d("RegisterActivity","Location not found:${it.message}")
        }

When I run the app, for some reason the downloadUrl (getDownloadUrl() which has been deprecated) gets called when the image upload is finished. This is the Debug log:

2020-04-10 07:15:44.849 12642-12642/com.example.chatapplication D/RegisterActivity: Location not found:Object does not exist at location.
2020-04-10 07:15:45.348 12642-12642/com.example.chatapplication D/RegisterActivity: Successfully uploaded the image: images/494ff560-4448-477b-bd6e-d71640eb6933

As seen above, the Successfully uploaded the image is logged after downloadUri is called. How do I make sure that downloadUrl is called after the image is uploaded?

2

2 Answers

0
votes

You should do it like this:

ref.putFile(selectedPhotoUri!!)
        .addOnSuccessListener {
             Log.d("RegisterActivity","Successfully uploaded the image: ${it.metadata?.path}")
           ref.downloadUrl.addOnSuccessListener {
             Log.d("RegisterActivity","File location: $it")
             saveUserToFirebaseDatabase(it.toString())
           }
        }
        .addOnFailureListener {
             Log.d("RegisterActivity", "Failed to upload image: ${it.message}")
        }

Call downloadUrl method after uploaded on success.

0
votes
val ref = storageRef.child("images/$fileName")
uploadTask = ref.putFile(file)

val urlTask = uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
    task.exception?.let {
        throw it
    }
}
ref.downloadUrl
}.addOnCompleteListener { task ->
  if (task.isSuccessful) {
    // here you get imageUrl
    val downloadUri = task.result
  } else {
    // failures
  }
}