Can't Get Actual Download Url Of An Image Uploaded In Firebase Storage
Solution 1:
Calling getDownloadUrl()
starts an asynchronous operation, which may take some time to complete. Because of this, your main code continues to run while the download URL is being retrieved to prevent blocking the user. Then when the download URL is available, your onSuccess
gets called. Because of this, by the time your intent.putExtra("imageURL", imageUrl)
now runs, the imageUrl = uri.toString()
hasn't run yet.
To see that this indeed true, I recommend putting some logging in the code to just show the flow, or running it in a debugger and setting breakpoints on the lines I indicated above.
To fix it, any code that needs the download URL, needs to be inside the onSuccess
, or be called from there. This applies not just here, but to all code that runs asynchronously, which includes most modern cloud APIs. So I recommend spending some time now studying this behavior, so that you're more comfortable with it going forward.
In your code:
finalStorageReferencestorageReference= FirebaseStorage.getInstance().getReference().child("images").child(imageName);
finalUploadTaskuploadTask= storageReference.putBytes(data);
uploadTask.addOnFailureListener(newOnFailureListener() {
@OverridepublicvoidonFailure(@NonNull Exception exception) {
Toast.makeText(CreateSnapActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(newOnSuccessListener<UploadTask.TaskSnapshot>() {
@OverridepublicvoidonSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = storageReference.getDownloadUrl().addOnSuccessListener(newOnSuccessListener<Uri>() {
@OverridepublicvoidonSuccess(Uri uri) {
imageUrl = uri.toString();
Toast.makeText(CreateSnapActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
Intentintent=newIntent(CreateSnapActivity.this, ChooseUserActivity.class);
intent.putExtra("imageName", imageName);
intent.putExtra("imageURL", imageUrl);
intent.putExtra("message", captionEditText.getText().toString());
startActivity(intent);
}
});
}
});
Also see:
Solution 2:
imageURL is a task.You are trying to print a task. not task's result. please try this code:
Task<Uri> imageURL = storageReference.getDownloadUrl();
Log.i("URL", imageURL.toString());
Log.i("URL", imageURL.result.toString());
Post a Comment for "Can't Get Actual Download Url Of An Image Uploaded In Firebase Storage"