and-nd-firebase: UploadTask.TaskSnapshot doesn't have getDownloadUrl() method

I’m following a tutorial teaching how to upload images to Firebase. At certain moment the instructor will write the code to get the download URL after uploading by using getDownloadUrl() method from UploadTask.TaskSnapshot, but for me, this method doesn’t exist.

enter image description here

Based on another code I found, I tried the following:

OnSuccessListener<UploadTask.TaskSnapshot> upload = new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        ChatroomMessage message = new ChatroomMessage(null, mUsername, taskSnapshot.getDownloadUrl());
        mMessagesDatabaseReference.push().setValue(message);
    }
};

Because it is similar to what’s shown in the documentation, but I didn’t understand it very well. How to implement it?

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 11
  • Comments: 41

Most upvoted comments

Yes they deprecated and then removed that method. I use the following code, similar to what is written in the docs.

photoStorageReference.putFile(selectedImageUri).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 photoStorageReference.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
            mMessagesDatabaseReference.push().setValue(friendlyMessage);
        } else {
            Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

taskSnapshot.getStorage().getDownloadUrl().toString()

@DevRyz3n running this command would raise FileNotFoundException as the returned value is not the download url for file. Instead try this code where I have created a Task object to perform getDownloadUrl() task, waited for its completion in the main thread and then obtained the URL through getResult() function.

@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
     Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
     while (!urlTask.isSuccessful());
     Uri downloadUrl = urlTask.getResult();
     FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
     mDatabaseReference.push().setValue(friendlyMessage);
}
  //putting image into storage
            final StorageReference filePath= mStorageRef.child("Users_Profile_Picture").child(UserIdString+".jpg");
            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if(task.isSuccessful()){
            //getting storage string

                      // String DownloadUrl= task.getResult().getDownloadUrl().toString();

                       // String DownloadUrl= task.getResult().getStorage().getDownloadUrl().toString();

                        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String downloadUrl = uri.toString();

                                UserDataBase.child("Image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){
                                            progressDialog.dismiss();
                                            Toast.makeText(SettingActivity.this,"Your picture Saved successfully",Toast.LENGTH_SHORT) .show();

                                        }else{
                                            Toast.makeText(SettingActivity.this,"Problem occurred while tryng to save your picture..",Toast.LENGTH_SHORT) .show();
                                        }
                                    }
                                });
                            }
                        });


            //uploading into database


                    }else{
                        Toast.makeText(SettingActivity.this,"Your picture did NOT saved",Toast.LENGTH_SHORT) .show();
                        progressDialog.dismiss();
                    }
                }
            });

Try this, works good !!! believe me… put this in the onActivityResult method…😃

@ChutiBro try this

StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
        while(!uriTask.isComplete());
        Uri downloadUrl = uriTask.getResult();



        // Set the download URL to the message box, so that the user can send it to the database
        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
        mMessagesDatabaseReference.push().setValue(friendlyMessage);
     }
 });

` package com.google.firebase.udacity.friendlychat;

import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast;

import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.firebase.ui.auth.AuthUI; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask;

import java.util.ArrayList; import java.util.Arrays; import java.util.List;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
public static final int RC_SIGN_IN = 1;
// Integer constant for startActivityResult
private static final int RC_PHOTO_PICKER = 2;



private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;


private String mUsername;



// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;



@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mUsername = ANONYMOUS;

    // Initialize Firebase components
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseStorage = FirebaseStorage.getInstance();

    mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
    mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos"); // chat_photos is the folder name in firebase consol

    // Initialize references to views
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageListView = (ListView) findViewById(R.id.messageListView);
    mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mSendButton = (Button) findViewById(R.id.sendButton);

    // Initialize message ListView and its adapter
    List<FriendlyMessage> friendlyMessages = new ArrayList<>();
    mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
    mMessageListView.setAdapter(mMessageAdapter);

    // Initialize progress bar
    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    // ImagePickerButton shows an image picker to upload a image for a message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Fire an intent to show an image picker
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });



    // Enable Send button when there's text to send
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }



        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }


        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});


    // Send button sends a message and clears the EditText
    mSendButton.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
            mMessagesDatabaseReference.push().setValue(friendlyMessage);
            // Clear input box
            mMessageEditText.setText("");
        }

    });



    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                onSignedInInitialize(user.getDisplayName());
            } else {
                // User is signed out
                onSignedOutCleanup();
                //Source https://github.com/firebase/FirebaseUI-Android
                startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                .setIsSmartLockEnabled(false)
                                .setAvailableProviders(Arrays.asList(
                                        new AuthUI.IdpConfig.GoogleBuilder().build(),
                                        new AuthUI.IdpConfig.EmailBuilder().build()))
                                .build(),
                        RC_SIGN_IN);
            }
        }

    };
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        // Sign_in succeeded, set up the UI
        Toast.makeText(this, "Siggned in!", Toast.LENGTH_SHORT).show();
    } else if (resultCode == RESULT_CANCELED) {
        // Sign in was canceled by the user, finish the activity
        Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
        finish();
    } else if (requestCode == RC_PHOTO_PICKER && requestCode == RESULT_OK) {
        Uri selectedimageUri = data.getData();

        // Get a reference to store file at chat_photos/<FILENAME>
        final StorageReference photoRef =
                mChatPhotosStorageReference.child(selectedimageUri.getLastPathSegment());

        // TODO Not working, method depricated
        // Upload file to Firebase Storage
        photoRef.putFile(selectedimageUri).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 photoRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    // When the image has successfully uploaded, we get its download URL
                    Uri downloadUri = task.getResult();

                    // Set the download URL to the message box, so that the user can send it to the database
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                } else {
                    Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}

@Override
protected void onResume() {
    super.onResume();
    mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}



@Override

protected void onPause() {
    super.onPause();
    if (mAuthStateListener != null) {
        mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
    }

    mMessageAdapter.clear();
    detachDatabaseReadListener();
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.sign_out_menu:
            // sign out
            AuthUI.getInstance().signOut(this);
            return true;
         default:
             return super.onOptionsItemSelected(item);
    }
}



private void onSignedInInitialize(String username) {
    mUsername = username;
    attachDatabaseReadListener();
}



private void onSignedOutCleanup() {
    mUsername = ANONYMOUS;
    mMessageAdapter.clear();
    detachDatabaseReadListener();
}



private void attachDatabaseReadListener() {
    if (mChildEventListener == null) {
        mChildEventListener = new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
                mMessageAdapter.add(friendlyMessage);
            }

            public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
            public void onChildRemoved(DataSnapshot dataSnapshot) {}
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
            public void onCancelled(DatabaseError databaseError) {}
        };

        mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
    }
}



private void detachDatabaseReadListener() {
    if (mChildEventListener != null) {
        mMessagesDatabaseReference.removeEventListener(mChildEventListener);
        mChildEventListener = null;
    }
}

}`

I use this code. but it does not store the photos in firebase. Not showing anything, but the app is not crashed. Help me to fix this.

<del>Try this <del> @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { FriendlyMessage message = new FriendlyMessage(null, mUsername , taskSnapshot.getStorage().getDownloadUrl().toString()); mMessagesDatabaseReference.push().setValue(message); }

<del>// FriendlyMessage(), the third parameter taskSnapshot.getStorage().getDownloadUrl().toString() </del>

I try to do it like this ↓↓↓ can work. Thanks @Parthav46

Uri uri = data.getData();
    if (uri != null) {
        final StorageReference imgReference = mChatPhotosStorageReference.child(uri.getLastPathSegment());
        UploadTask uploadTask = imgReference.putFile(uri);

        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 imgReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri taskResult = task.getResult();
                        FriendlyMessage message = new FriendlyMessage(null, mUsername, taskResult.toString());
                        mMessagesDatabaseReference.push().setValue(message);
                    }
                }
            });
        }

filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() { @Override public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) { if(task.isSuccessful()){ Toast.makeText(SettingActivity.this,“Your picture Saved successfully”,Toast.LENGTH_SHORT) .show(); String DownloadUrl=task.getResult().getStorage().getDownloadUrl().toString();

Have a look here.

Its as simple as using your storageRef to get the download url on condition the task was successfull.

      OnSuccessListener<UploadTask.TaskSnapshot> upload = new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                ChatroomMessage message = new ChatroomMessage(null, mUsername, ref.getDownloadUrl());
                mMessagesDatabaseReference.push().setValue(message);
            }
        };

Note the

    ref.getDownloadUrl() 

In place of

    taskSnapshot.getDownloadUrl() 

@ChutiBro try this

StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
        while(!uriTask.isComplete());
        Uri downloadUrl = uriTask.getResult();



        // Set the download URL to the message box, so that the user can send it to the database
        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
        mMessagesDatabaseReference.push().setValue(friendlyMessage);
     }
 });

This solution works best! for getting the photos to upload and store in the database! 😃 The .getDownloadURL is no longer available and deprecated.

i am currently having the same problem

public class FirebaseStorageHelper {

private static final String TAG = FirebaseStorageHelper.class.getCanonicalName();

private FirebaseStorage firebaseStorage;

private StorageReference rootRef;

private Context context;

public FirebaseStorageHelper(Context context){
    this.context = context;
    init();
}

private void init(){
    this.firebaseStorage = FirebaseStorage.getInstance();
    rootRef = firebaseStorage.getReferenceFromUrl("gs://fir-analyticexample.appspot.com");
}

public void saveProfileImageToCloud(String userId, Uri selectedImageUri, final ImageView imageView) {

    StorageReference photoParentRef = rootRef.child(userId);
    StorageReference photoRef = photoParentRef.child(selectedImageUri.getLastPathSegment());
    UploadTask uploadTask = photoRef.putFile(selectedImageUri);

    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d(TAG, "OnFailure " + e.getMessage());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            @SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl();
            Glide.with(context).load(downloadUrl.getPath()).into(imageView);
        }
    });

}

}

Just write this:- Uri downloaduri=taskSnapshot.getStorage().getDownloadUrl().getResult();

Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl(); while (!urlTask.isSuccessful()); Uri downloadUrl = urlTask.getResult();

I got it with this solution Check my code:

else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
            final Uri selectedImageUri = data.getData();
            //Toast.makeText(MainActivity.this, "Está no RC_PHOTO_picker! " + selectedImageUri.getLastPathSegment().toString(), Toast.LENGTH_SHORT).show();


            // Get a reference to store file at chat_photos/<FILENAME>
            StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

            // Upload a file to Filebase Storage
            photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                    while (!urlTask.isSuccessful());
                        Uri downloadUrl = urlTask.getResult();

                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                }
            });
        }

this code working in angular8

uploadfile(event:any){

const file:File=event.target.files[0]
console.log(file.name)

const metaData={'contenttype':file.type}
console.log(metaData)

const storageRef:firebase.storage.Reference =firebase.storage().ref(‘/photos’) const Uploadtask= storageRef.put(file) console.log(file.name)

  storageRef.getDownloadURL().then((url)=>{firebase.database().ref('/photos').set(url)})

}

thanks 1000 times Parthav46 I took your code and change it a litle bit and it works!!

private StorageReference userProfileImageRef;

userProfileImageRef = FirebaseStorage.getInstance().getReference().child( “Images” );

final StorageReference filePath = userProfileImageRef.child( userId + “.jpg” ); filePath.putFile( selectedImage ) .addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()); Uri downloadUrl = uriTask.getResult(); String dw = downloadUrl.toString(); Toast.makeText( ProfilActivity.this,dw,Toast.LENGTH_LONG ).show(); DocumentReference documentReference = fFirestore.collection(“users”).document(userId); Map<String,Object> data = new HashMap<>(); data.put( “Slika”,dw ); fFirestore.collection( “users” ).document(userId).set( data,SetOptions.merge() );

I faced the same problem but I got the answer

Just add .getStorage() infront of .getDownloadurl

to be like this below

.getStorage().getDownloadUrl 

LEAVE EVERYTHING IN THAT LINE DONT ALTER JUST ADD .getStorage()