Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the download url from Firebase Storage?

I want to get the Download Url from uploadTask.addOnProgressListener method of Firebase. How can I get the Download Url using following code?

    UploadTask uploadTask = storageRef.putBytes(data);

    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
    {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
        {
            Log.d("aaaaasessin",""+taskSnapshot.getTask().getResult());
        }
    });

I used taskSnapshot.getTask().getResult() but that is not working.

like image 979
ajay dhadhal Avatar asked Nov 14 '18 12:11

ajay dhadhal


1 Answers

Edit Aug 22th 2019:

There is a new method recently added to StorageReference's class in the Android SDK named list().

To solve this, you need to loop over the ListResult and call getDownloadUrl() to get the download URLs of each file. Remember that getDownloadUrl() method is asynchronous, so it returns a Task object. See below for details. I have even written an article regarding this topic called:

  • How to upload an image to Cloud Storage and save the URL in Firestore?

In order to get the download url, you need to use addOnSuccessListener, like in the following lines of code:

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();

                //Do what you need to do with url
            }
        });
    }
});

As in the Firebase release notes on May 23, 2018 is mentioned that:

Cloud Storage version 16.0.1

Removed the deprecated StorageMetadata.getDownloadUrl() and UploadTask.TaskSnapshot.getDownloadUrl() methods. To get a current download URL, use StorageReference.getDownloadUr().

So now when calling getDownloadUrl() on a StorageReference object it returns a Task object and not an Uri object anymore.

Please also rememeber, neither the success listener nor the failure listener (if you intend to use it), will be called if your device cannot reach Firebase Storage backend. The success/failure listeners will only be called once the data is committed to, or rejected by the Firebase servers.

like image 117
Alex Mamo Avatar answered Oct 26 '22 11:10

Alex Mamo