Reputation: 5
I'm uploading an image to Firebase Storage, I need the image URL in the Storage to use it then to insert it within a document in FireStore. How to get the url after the upload process is finished and not before it finished?
public String uploadImage(byte[] bytes) {
try {
final StorageReference ref = storage.child("images/" + new Date().toString());
ref.putBytes(bytes)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
res = uri.toString();
return;
}
});
}
});
System.out.println("RES : " + res);
return res;
}catch (NullPointerException e){
return null;
}
}
//the variable res must return a not null value.
Upvotes: 0
Views: 208
Reputation: 385
we can get the URL of a file from taskSnapshot
, like that:
public String uploadImage(byte[] bytes) {
try {
final StorageReference ref = storage.child("images/" + new Date().toString());
ref.putBytes(bytes)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful()) ;
Uri downloadUrl = urlTask.getResult();
}
});
System.out.println("RES : " + res);
return res;
}catch (NullPointerException e){
return null;
}
}
Hope it helps you!
Upvotes: 0
Reputation: 4809
Ref :: Image not retrieving from Firebase
//add file on Firebase and got Download Link
filePath.putFile(imageUri).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 filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downUri = task.getResult();
Log.d(TAG, "onComplete: Url: "+ downUri.toString());
}
}
});
Upvotes: 0