0

I am trying to store the url in the firebasedatabase of images i upload into the firebase storage.

I have tried some video guides but most of them are outdated.I am trying to use downloadUrl to fetch url but its not working. I am new to coding and i d appreciate any kind of advice. I have tried Firebase Documentation but i am unable to apply it into my code.

    if (mImageUri != null)
    {
        val fileName= edit_text_file_name.text.toString()
        val fileReference = mStorageRef!!.child(fileName + "." + getFileExtension(mImageUri!!)
        )
        mUploadTask = fileReference.putFile(mImageUri!!)
            .addOnSuccessListener { taskSnapshot ->

                val name = taskSnapshot.metadata!!.name
                val imageUrl= taskSnapshot.metadata!!.reference!!.downloadUrl.toString()

The problem here is in the line above i think with val imageUrl

                writeNewImageInfoToDB(name!!, imageUrl)
                Toast.makeText(this@ActivityUpload, "Upload successful", Toast.LENGTH_LONG).show()
            }
            .addOnFailureListener { e -> Toast.makeText(this@ActivityUpload, e.message, Toast.LENGTH_SHORT).show() }
            .addOnProgressListener { taskSnapshot ->
                val progress = (100.0 * taskSnapshot.bytesTransferred / taskSnapshot.totalByteCount)
                mProgressBar!!.progress = progress.toInt()
            }

I expect the above code to give me the URL of the image i uploaded but instead i get

com.google.android.gms.tasks.zzu@5a826e5" in my database whereas i am expecting a firebase url like firebasestorage.googleapis.com/v0/b/-------`

Anas Mehar
  • 2,739
  • 14
  • 25
Umer Qureshi
  • 115
  • 1
  • 9

1 Answers1

1

You are getting:

com.google.android.gms.tasks.zzu@5a826e5

And not the actual url because this is the address from memory of your downloadUrl object which is of type Task<Uri> and not the actual Uri.

According to the official documentation regarding on how to get a download URL:

After uploading a file, you can get a URL to download the file by calling the getDownloadUrl() method on the StorageReference:

val ref = storageRef.child(fileName + "." + getFileExtension(mImageUri!!))
uploadTask = ref.putFile(file)

val urlTask = uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
    if (!task.isSuccessful) {
        task.exception?.let {
            throw it
        }
    }
    return@Continuation ref.downloadUrl
}).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val downloadUri = task.result
    } else {
        // Handle failures
        // ...
    }
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193