Reputation: 158
Hello I am trying to retrieve the Image URL from Firebase storage after image upload and display it in a Toast from the Image Upload method which would return the URL as a string.
I am able to get the URL but my toast runs before the image upload is complete hence returning an empty string response in place of the URL.
What i want to achieve is to get the image URL and then display it in the toast outside the Upload method if the upload is successful
This is what i have tried;
insertImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(TestFirebaseImageUpload.this, firebaseImageUpload(filePath), Toast.LENGTH_SHORT).show();
}
});
when the insertImage button is clicked it displays a toast which should contain the URL of the image which is gotten by sending the file uri to the firebaseImageUploadMethod.
This is my firebaseImage upload Method
public String firebaseImageUpload(Uri filePath) {
if (filePath != null) {
// Setting progressDialog Title.
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(" Uploading...");
progressDialog.show();
ref = imagePath.child("images/" + UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(TestFirebaseImageUpload.this, "Uploaded ... ", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
URL = uri.toString();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
URL = "";
Toast.makeText(TestFirebaseImageUpload.this, "Not Uploaded ... ", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
return URL;
}
What i want is to display the URL in the toast which is displayed when the insertImage Button is clicked.
Thanks
Upvotes: 0
Views: 183
Reputation: 988
You can set up a callback
onClick(){
firebaseImageUpload(filePath, Callback)
}
onUploaded(){
// Display toast here
}
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
URL = uri.toString();
callback.onUploaded(URL);
}
});
interface Callback{
void onUploaded(String url)
}
Upvotes: 2