Once you have uploaded a file to Firebase how can you get it's URL so that you can store that for later use? I want to write the URL to a Firebase Database so that other users can access the image.
I am uploading the file like so:
public void uploadFile()
{
StorageReference filepath = mstorageRef.child("folder").child(filename);
Uri File= Uri.fromFile(new File(mFileName));
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
}
I have confirmed that the files are in fact uploading so now I just need the URL which I can write to my Database. However when I tried to do this:
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
It gives me an error and says This method should only be accessed from tests or within private scope
I'm not sure what that means and I also don't know why I would be getting that error since I'm following this example provided by Firebase.
Is there a new way of getting the URL?
Also, is that URL unique to that item in particular? Meaning if I store it to a database and try to access it later will I be able to do so?
You're using UploadTask.getDownloadUrl()
which is deprecated. You can use StorageReference.getDownloadUrl().
In your case you can try this as -
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
//Do what you want with the url
}
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
Take care that StorageReference.getDownloadUrl()
returns Task, which must be handled asynchronously, you cannot do Uri downloadUrl = photoRef.getDownloadUrl().getResult();
else you will get java.lang.IllegalStateException: Task is not yet complete