9

To upload images to Firebase Storage I am attaching addOnSuccessListener on the instance of the StorageReference. While overriding onSuccess method I am calling getDownloadUrl() on the instance of taskSnapshot but it is giving me an error saying

Can't resolve method getDownloadUrl()

This app I had created 2 months ago, earlier this app was working fine and getDownloadUrl() was working fine as well. Also, in taskSnapshot instance when I press Ctrl+space, in the suggestions I don't find getDownloadUrl() method. Why is it happening?

Code to onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == RC_SIGN_IN) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, "Signed in!!!1", Toast.LENGTH_SHORT).show();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Failed to sign in", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
        Uri selectedPhoto = data.getData();

        StorageReference localRefrence = storageReference.child(selectedPhoto.getLastPathSegment());

        //  Uploading the file on the storage
        localRefrence.putFile(selectedPhoto).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                 Uri downloadUrl = taskSnapshot.getDownloadUrl();

                FriendlyMessage message = new FriendlyMessage(mUsername, null, downloadUrl.toString());
                databaseReference.push().setValue(message);
            }
        });
    }
}
Neeraj Sewani
  • 3,952
  • 6
  • 38
  • 55

7 Answers7

24

The Firebase API has changed.

May 23, 2018

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().

UploadTask.TaskSnapshot has a method named getMetadata() which returns a StorageMetadata object.

This StorageMetadata object contains a method named getReference() which returns a StorageReference object.

That StorageReference object contains the getDownloadUrl() method, which now returns a Task object instead of an Uri object.

This Task must then be listened upon in order to obtain the Uri, which can be done asynchronously or in a blocking manner; see the Tasks API for that.

Community
  • 1
  • 1
Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • 1
    I had invoked `getDownloadUrl()` on the instance of `TaskSnapshot` and at that time it was returning `Uri` but now it's returning `Task`. Did the method of invoking `getDownloadUrl()` method get change in the past few months? – Neeraj Sewani Jun 02 '18 at 21:06
  • 1
    See the modified answer, it got deprecated on May 23 2018. So yes, you now must get the Uri via the Task object. – Daniel F Jun 02 '18 at 21:12
  • 1
    @Daniel F In `onSuccess()` I wrote `Task downloadUri=taskSnapshot.getMetadata().getReference().getDownloadUrl(); Log.i("url:",downloadUri.getResult().toString());` but it thows `Exception` 'java.lang.IllegalStateException: Task is not yet complete' Please help – Bhagyashri Jun 12 '18 at 09:21
  • 2
    @userI The downloadUri is a Task. You have two options. either call `Tasks.await(downloadUri)`before you call `downloadUri.getResult()` (but only do this if you are in a background thread!!!), or use `downloadUri.addOnCompleteListener(...)` as shown in https://developers.google.com/android/guides/tasks – Daniel F Jun 12 '18 at 09:47
  • 3
    @userI I must correct one thing: if you are in a background thread, you can call `theUri = Tasks.await(downloadUri)` because `downloadUri.getResult()` is only called inside `downloadUri.addOnCompleteListener(...)`. It could possibly also be called after `Tasks.await(downloadUri)`, but there would be no need to do so since `await` is already returning the result. – Daniel F Jun 12 '18 at 09:58
  • @Daniel F It worked.Thank you so much for your quick help. – Bhagyashri Jun 12 '18 at 10:01
6

You wont get the download url of image now using

profileImageUrl = taskSnapshot.getDownloadUrl().toString(); this method is deprecated.

Instead you can use the below method

uniqueId = UUID.randomUUID().toString();
ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);

Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
UploadTask uploadTask = ur_firebase_reference.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 ur_firebase_reference.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            System.out.println("Upload " + downloadUri);
            Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
            if (downloadUri != null) {

                String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
                System.out.println("Upload " + photoStringLink);

            }

        } else {
            // Handle failures
            // ...
        }
    }
});
MIDHUN CEASAR
  • 131
  • 2
  • 9
  • Thank you, this works perfectly, I don't know why your answer is still under-rated. A similar solution can be found on github by LucaUburti, in his post, via this link: [firebase-storage-getDownloadUrl solution link](https://github.com/udacity/and-nd-firebase/issues/41) – Brian Oct 20 '18 at 08:29
4
final StorageReference filePath = mImageStore.child("profile_images").child("full_image").child(userId + ".jpg");
                filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        //Bitmap hochladen
                        uploadBitMap(uri.toString());
                    }
                });
1

The .getDownloadURL is no longer available and deprecated. from the documentation Task<Uri> and getdownloadUrl(); Asynchronously retrieves a long lived download URL with a revokable token. see documentation

 @Override 
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
     Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl(); 
    while (!urlTask.isSuccessful());
     Uri downloadUrl = urlTask.getResult();
//continue with your code
griffins
  • 7,079
  • 4
  • 29
  • 54
1

The getDownloadUrl method has been depreceated. Instead use the following taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

epiphmo
  • 11
  • 1
0

You should try this one. Understand it and try to implement in yours

buttonSetup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name = editText_name.getText().toString();
            if (!TextUtils.isEmpty(name) && mainImageURI != null) {
                final String user_id = firebaseAuth.getCurrentUser().getUid();
                progressBar_setup.setVisibility(View.VISIBLE);
                final StorageReference image_path = storageReference.child("profile_images").child(user_id + ".jpg");
                UploadTask uploadTask = image_path.putFile(mainImageURI);

                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();
                        }
                        return image_path.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()){
                            Uri downloadUrl = task.getResult();
                            Log.i("The URL : ", downloadUrl.toString());
                        }
                    }
                });
            }
        }
    });
Agung Pramono
  • 429
  • 4
  • 7
0

Try

{
    firebase.storage()
    .child()
    .getDownloadURL().then()
}
David Buck
  • 3,752
  • 35
  • 31
  • 35