1

I'm trying to get the URL of the uploaded file, but I get this: com.google.android.gms.tasks.zzu@a12a0cb or something similar.

Here is the code I've tried (kotlin):

val uid = UUID.randomUUID().toString()

val storageRef = FirebaseStorage.getInstance().reference.child("content/$uid/$uid.jpg")

storageRef.putFile(file).addOnSuccessListener { taskSnapShot ->
    val downloadUrl = storageRef.downloadUrl
    FirebaseDatabase.getInstance().reference.child("Photos").child(date).push().setValue(downloadUrl)
}

But it doesn't work. Also I've tried the following code:

val uid = UUID.randomUUID().toString()

val storageRef = FirebaseStorage.getInstance().reference.child("content/$uid/$uid.jpg")

storageRef.putFile(file).addOnSuccessListener (
      object : OnSuccessListener<UploadTask.TaskSnapshot> {
          override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
              val downloadUrl = storageRef.downloadUrl
              FirebaseDatabase.getInstance().reference.child("Photos").child(date).push().setValue(downloadUrl)
          }
      }
)

But the result is the same. I'm still getting com.google.android.gms.tasks.zzu@a12a0cb inserted into my database, instead of the URL. What I'm doing wrong? I've spent all my day trying to figure it out, please help.

Hemk
  • 11
  • 2

7 Answers7

3

I had the same problem. I just solved it. I can not say exactly why it did not work with other syntaxes, but I got the result doing it this way: (Firebase implementation version: 16.0.1 / Kotlin)

mReference.putFile (uri) .addOnFailureListener {
          // failure
       } .addOnSuccessListener () {taskSnapshot -> 
         // success
             mReference.downloadUrl.addOnCompleteListener () {taskSnapshot ->

                 var url = taskSnapshot.result
                 println ("url =" + url.toString ())

             }
  }
MSilva
  • 151
  • 1
  • 6
1

Here is a part of the code of my project, which had the same problem of yours, but now working fine after making necessary modifications, make changes accordingly.

final StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");


            filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {

                    filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {

                            if (task.isSuccessful()){

                                String download_url=uri.toString();//Here is the URL

                                mUserDatabase.child("image").setValue(download_url)/*Storing the URL in the Firebase database*/
                                 .addOnCompleteListener(new OnCompleteListener<Void>() {

                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                        if (task.isSuccessful()) {

                                            /*mProgressDialog.dismiss();
                                            Toast.makeText(SettingsActivity.this, "Success Uploading", Toast.LENGTH_LONG).show();*/

                                        }
                                    }
                                });

                            }else {
                                /*Toast.makeText(SettingsActivity.this, "Error in uploading!", Toast.LENGTH_LONG).show();
                                mProgressDialog.dismiss();*/
                            }

                        }
                    });

                }
            });
1

The key point here in getting the download URL is to understand that there are multiple Task values that are being used to finally get the actual Uri.

The dbRef.downloadUrl actually returns a Task itself. And we retrieve the Uri of the uploaded file from this Task.

Here is a pseudo-code:

        val finalStoragePathRef = mStorageReference.child(selectedImageUri!!.lastPathSegment!!)

        //putFile() returns an UploadTask and you can call the listener methods on this task            
        finalStoragePathRef.putFile(selectedImageUri)
                        .addOnFailureListener {
                            //Failure
                        }.addOnSuccessListener { //If upload was a success, get the downloadUrl

        //downloadUrl() returns a Task with the Uri
        //Extract the Uri from addOnCompleteListener method of the downloadUrl() method

                            finalStoragePathRef.downloadUrl.addOnCompleteListener {
                                val url = it.result
                                Log.i (TAG, "URL: " + url.toString ())
    //Create your data model
                                val message = Message(...,mUsername,url.toString())
    //Add the data to your database                            
mMessagesDatabaseReference.push().setValue(message)
                            }
                        }

Hope this makes sense. A lot of the older methods are now deprecated and its best to refer to the documentation to get a better idea: https://firebase.google.com/docs/storage/android/upload-files

srinij
  • 471
  • 6
  • 10
0

You may be using an old version of Firebase-storage. The way you want to get the URL is deprecated, take a look at the change log Cloud Storage version 16.0.1

I dont have the Kotlin code, but the java code is

final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }

        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
        } else {
            // Handle failures
            // ...
        }
    }
});

This code you can find in the Android documentation of Firebase Storage in the section Android > Upload Files > Get a download URL

Yayo Arellano
  • 3,575
  • 23
  • 28
  • Can I use older vesion of firebase storage? Ex. 15.0.2? This version is much easier to use, the API is simpler to understand. – Hemk Jun 28 '18 at 10:34
  • I needed to update my code because i had the same problem as you, suddenly it stop working. Now is a little more complicated to get the downloadURL but is the only way i know. I suggest you update because that also bring improvements and bug fixes. – Yayo Arellano Jun 28 '18 at 15:51
0

This Code worked for me

//Data is the uri of the file
  UploadTask uploadTask =mProfileStorageRef.child("profilePic").putFile(data);
 uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {

            task.getResult().getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {

                    if (task.isSuccessful()) {

                        //Url is here
                        String url = uri.toString();



                            }
                        });
0

In case you are working with kotlin, this code is based on the official documentation and works like a charm.

    fun fileUpload() {


    mFireBaseStorage = FirebaseStorage.getInstance()
    mphotoStorageReference = mFireBaseStorage.getReference().child("alvaras")

    //in case you want to compress your bitmap before upload
    val bmp: Bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath) //filepath is the URI from the onActivityResult
    val baos: ByteArrayOutputStream = ByteArrayOutputStream()
    bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos) //25 is the compression, cane be anything between 1 and 100, but 100 is no compression

    //get the uri from the bitmap
    val tempUri: Uri = getImageUri(this, bmp)
    //transform the new compressed bmp in filepath uri
    filePath = tempUri //update the filePath variable

var uploadTask = mphotoStorageReference.putFile(filePath)

    val urlTask = uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
        if (!task.isSuccessful) {
            task.exception?.let {
                throw it
            }
        }
        return@Continuation mphotoStorageReference.downloadUrl
    }).addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val downloadUri = task.result

            urifinal = downloadUri.toString() //this is the url you want
            val imageView: ImageView = findViewById(R.id.imageView1)

            //show it in a imageview with glide with the url
            Glide.with(this@MapsActivity).load(urifinal).into(imageView)
            imageView.visibility = View.VISIBLE

        } else {
            // Handle failures
        Toast.makeText(this, "An error occur", Toast.LENGTH_SHORT).show()
            // ...
        }
    }


    }
Thiago Silva
  • 670
  • 6
  • 18
0

Using Kotlin

There is a little error in the official doc

but it's corrected here

X-Black...
  • 1,376
  • 2
  • 20
  • 28