I am getting an error while uploading image URL to firebase database from the firebase storage

82 Views Asked by At

I got this in firebase: I got this in firebase

private fun uploadToFireBase(imageUri: Uri) {
    binding.progressBar.visibility = View.VISIBLE
    val fileRef : StorageReference = storageReference.child("${System.currentTimeMillis()}.${getFileExtension(imageUri)}")
    fileRef.putFile(imageUri).addOnSuccessListener {


        fileRef.downloadUrl.addOnSuccessListener {
            binding.progressBar.visibility = View.VISIBLE

            val hackathonModel = HackathonModel(binding.HackTitleET.text.toString() , binding.HackUrlET.text.toString() ,
                binding.HackLocationET.text.toString(), imageUri.toString()
            )

            val hackathonModelId : String? = root.push().key
            root.child("HackathonsUsers").child(firebaseAuth.currentUser!!.uid).child(hackathonModelId.toString()).setValue(hackathonModel)
            root.child("AllHackathons").child(hackathonModelId.toString()).setValue(hackathonModel)


            Toast.makeText(this, "Hackathon Uploaded Successfully", Toast.LENGTH_SHORT).show()
            val intent = Intent(this , MainActivity::class.java)
            startActivity(intent)
            finish()
        }

    }.addOnProgressListener {
        binding.progressBar.visibility = View.VISIBLE
    }.addOnFailureListener{
        binding.progressBar.visibility = View.INVISIBLE
        binding.postHackBT.visibility= View.VISIBLE
        Toast.makeText(this, "Uploading Failed", Toast.LENGTH_SHORT).show()
    }
}

private fun getFileExtension(imageUri: Uri): String? {
    val cr : ContentResolver = contentResolver
    val mime : MimeTypeMap = MimeTypeMap.getSingleton()
    return mime.getExtensionFromMimeType(cr.getType(imageUri))
}

how to fix this error and get a link in correct form not in this form (content://com.android.providers.media.documents/document/image%3A428613)?

1

There are 1 best solutions below

0
Frank van Puffelen On

You're creating your model with:

val hackathonModel = HackathonModel(binding.HackTitleET.text.toString() , binding.HackUrlET.text.toString() ,
    binding.HackLocationET.text.toString(), imageUri.toString()
)

That last argument is imageUri.toString(), which is the path to the image on your local Android device, and not the download URL that you told Firebase to generate for you.

To get the latter:

fileRef.downloadUrl.addOnSuccessListener { task ->
    binding.progressBar.visibility = View.VISIBLE

    if (task.isSuccessful) {
        val downloadUri = task.result

        val hackathonModel = HackathonModel(binding.HackTitleET.text.toString() , binding.HackUrlET.text.toString() ,
            binding.HackLocationET.text.toString(), downloadUri.toString()
        )
        ...

Also see the Firebase documentation on getting the download URL after uploading a file.