21
private void uploadImageToFirebaseStorage() {
    StorageReference profileImageRef =
        FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

    if (uriProfileImage != null) {
        progressBar.setVisibility(View.VISIBLE);
        profileImageRef.putFile(uriProfileImage)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                    progressBar.setVisibility(View.GONE);
                    profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    }
}

taskSnapshot.getDownloadUrl() method not working comes up with red line under it

25 Answers 25

65

Edit: see this comment on why the approach in this answer doesn't work:

firebaser here This answer is wrong. While it at first may appear to work (since it compiles) the result of getDownloadUrl().toString() is not a download URL, but a string representation of a Task object. For a better answer, see stackoverflow.com/a/55503926 or the sample in the Firebase documentation.

Original answer below...


In Firebase Storage API version 16.0.1, the getDownloadUrl() method using taskSnapshot object has changed. now you can use,

taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

to get download url from the firebase storage.

5
  • 3
    I'm using Firebase Storage API version 16.0.5 and the task has to be referenced as uploadTask.getResult().getMetadata().getReference().getDownloadUrl().toString();
    – LeleMarieC
    Jan 17, 2019 at 2:43
  • now some user has to use StorageReference (Path Where you upload your file) object and then getDownloadUrl() and then add CompleteListener to get the direct download url for the particular document of the reference. Jan 23, 2019 at 18:23
  • 3
    the method is not returning the download URL (that is expected). Link - stackoverflow.com/a/55503926/7764015 .This code is giving the expected output. (The actual download URL for the file) Dec 12, 2019 at 10:23
  • 4
    firebaser here This answer is wrong. While it at first may appear to work (since it compiles) the result of getDownloadUrl().toString() is not a download URL, but a string representation of a Task object. For a better answer, see stackoverflow.com/a/55503926 or the sample in the Firebase documentation: firebase.google.com/docs/storage/android/… Mar 27, 2020 at 21:00
  • Solved my Error..Thanks
    – Faran
    Aug 20 at 4:52
29

To get imageUrl path from storage use this code:

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        if (taskSnapshot.getMetadata() != null) {
            if (taskSnapshot.getMetadata().getReference() != null) {
                Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String imageUrl = uri.toString();
                        //createNewPost(imageUrl);
                    }
                });
            }
        }
    }});

that is all 😉

NOTE: Do not forget initialize StorageReference and UploadTask in your uploadFile method.

12

Try Using this it will download the image from FireBase storage

FireBase Libraries versions 16.0.1

Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
      @Override
      public void onSuccess(Uri uri) {
             String photoStringLink = uri.toString();
      }
});
1
4

I faced the similar error I solved it with this method. Hope it helps

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                task.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String photoLink = uri.toString();
                        Map userInfo = new HashMap();
                        userInfo.put("profileImageUrl", photoLink);
                        mUserDatabase.updateChildren(userInfo);
                    }
                });
                finish();
                return;
            }
        });
4
 ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                            @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                                changeProfilePic(String.valueOf(task.getResult()));//gives image or file string url
                            }
                        });

try this code will work for sure

1
  • This answer is recommended.
    – Umar Ata
    Nov 29, 2019 at 13:44
2

My Google Firebase Plugins in build.gradle(Module: app):

implementation 'com.firebaseui:firebase-ui-database:3.3.1'
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'

build.gradle(Project):

 classpath 'com.google.gms:google-services:3.2.1'

My upload() function and fetching uploaded data from Firebase storage :

private void upload() {
    if (filePath!=null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        final StorageReference ref = storageReference.child(new StringBuilder("images/").append(UUID.randomUUID().toString()).toString());
        uploadTask = ref.putFile(filePath);

        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();
                }

                return ref.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    progressDialog.dismiss();
                    // Continue with the task to get the download URL
                    saveUrlToCategory(downloadUri.toString(),categoryIdSelect);
                } else {
                    Toast.makeText(UploadWallpaper.this, "Fail UPLOAD", Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                progressDialog.setMessage("Uploaded: ");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(UploadWallpaper.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

FOR THOSE WHO ARE USING LATEST FIREBASE VERSION taskSnapshot.getDownloadUrl() method is DEPRECATED or OBSOLETE !!

2

I'm using Firebase Storage API version 16.0.5 and the task has to be referenced as

 someTask.getResult().getMetadata().getReference().getDownloadUrl().toString();

hope this helps!

1

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
                // ...
            }
        }
    });
1
//upload button onClick
public void uploadImage(View view){
    openImage()
}

private Uri imageUri;

ProgressDialog pd;

//Call open Image from any onClick Listener
private void openImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,IMAGE_REQUEST);
}

private void uploadImage(){
    pd = new ProgressDialog(mContext);
    pd.setMessage("Uploading...");
    pd.show();

    if (imageUri != null){
        final StorageReference fileReference = storageReference.child(userID
                + "."+"jpg");

        // Get the data from an ImageView as bytes
        _profilePicture.setDrawingCacheEnabled(true);
        _profilePicture.buildDrawingCache();

        //Bitmap bitmap = ((BitmapDrawable) _profilePicture.getDrawable()).getBitmap();

        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();

        UploadTask uploadTask = fileReference.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
                pd.dismiss();
                Log.e("Data Upload: ", "Failled");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                // ...
                Log.e("Data Upload: ", "success");
                Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String downloadLink = uri.toString();
                        Log.e("download url : ", downloadLink);
                    }
                });

                pd.dismiss();

            }
        });

    }else {
        Toast.makeText(getApplicationContext(),"No Image Selected", Toast.LENGTH_SHORT).show();
    }
}

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

    Bitmap bitmap = null;
    if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
        imageUri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
            _profilePicture1.setImageBitmap(bitmap);
            _profilePicture1.setDrawingCacheEnabled(true);
            _profilePicture1.buildDrawingCache();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (uploadTask != null && uploadTask.isInProgress()){
            Toast.makeText(mContext,"Upload in Progress!", Toast.LENGTH_SHORT).show();
        }
        else {
            try{
                uploadImage();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
1
taskSnapshot.**getDownloadUrl**().toString(); //deprecated and removed

use below code for downloading Url

final StorageReference profileImageRef= FirebaseStorage.getInstance().getReference("profilepics/" + "abc_10123" + ".jpg");

profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
        {
            @Override
            public void onSuccess(Uri downloadUrl) 
            {                
               //do something with downloadurl
            } 
        });
2
  • yes. it needs to be made final. please mark as solution if it helps you May 30, 2018 at 9:37
  • final StorageReference profileImageRef= FirebaseStorage.getInstance().getReference("profilepics/" +" abc_10123" + ".jpg"); May 30, 2018 at 9:40
0

for latest version try

profileImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();
0

Try using this:

taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
0

FirebaseStorage Library version 19.0.1 works with

String download_image_path = task.getResult().getUploadSessionUri().toString();
0
//firebase database
implementation 'com.google.firebase:firebase-database:15.0.0'
//firebase storage
implementation 'com.google.firebase:firebase-storage:15.0.0'

.getDownloadUrl() method is removed from later versions , i have changed it to 15.0.0 and works perfectly fine.You can find these in build.gradle(module:app)

0

Only that...

taskSnapshot.getStorage().getDownloadUrl();

Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
   @Override
   public void onSuccess(Uri uri) {
       String photoStringLink = uri.toString();
       mDatavaseRef.push().setValue(photoStringLink);
   }
});
0

This will work:

.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {


                Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String photoStringLink = uri.toString();
                        Log.i("urlimage", photoStringLink);
                    }
                });
            }
        });
0

Try this:

Uri download_uri ;

final Map<String, String> userData = new HashMap<>();
    if (task != null) {
       //download_uri = task.getResult().getDownloadUrl();
      download_uri = task.getResult().getUploadSessionUri();
    }
    else {
        download_uri= imageUri;
    }

userData.put("Image", download_uri.toString());
userData.put("name",username);
userData.put("category",category);
userData.put("status",status);
0

this is help help me with the last dependencies in 04/2020

     // Get a reference to store file at chat_photos/<FILENAME>
     final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
     photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //When the image has successfully uploaded, get its downloadURL
                        photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                Uri dlUri = uri;
                                FriendlyMessage friendlyMessage = new 
                                  FriendlyMessage(null, mUsername, dlUri.toString());
0

Use Firebase storage version 15.0.0.

Uri downloadUrl=taskSnapshot.getDownloadUrl().toString();
0
0

you can also use Picasso dependencies . its easy to use for uploading image in firebase.

ActivityFile:

 Picasso.get().load(uriImage).into(ImageUri);

app-gradle:

com.squareup.picasso:picasso:2.71828
0

This will Solve Your Problem....

if(uploadTask.isSuccessfull()){
Task<Uri> uriTask=uploadTask.getResult().getStorage().getDownloadUrl();                                               while(!uriTask.isSuccessful());
Uri downloadUri=uriTask.getResult();
final String download_url=downloadUri.toString();
}
1
  • 1
    could you explain why its going to solve his problem?
    – CoderUni
    Oct 14, 2020 at 5:04
0
 private void uploadImageTask() {
    Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Pictures/OnShot.jpg"));
    StorageReference storageReference = this.storageReference.child("images/" + UUID.randomUUID().toString());
    storageReference.putFile(uri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {
                            Log.d(TAG, "Download URL: " + String.valueOf(task.getResult()));
                        }
                    });
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    // ...
                }
            });
}
-1

I still having this error. What might be wrong? I already changed the permissions, and users to anonymous.

enter image description here

-1

For Java Code

String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();

For Kotlin

val downloadUrl = taskSnapshot.getMetadata()?.getReference()?.getDownloadUrl()?.toString()
-1

there is nothing wrong with the depencies. You just have to downgrade your firebase depencies. This is because it hasnt been updated yet..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.