How To Return A Variable From A Listener Method
In the below code, I am declaring class variable downloadUrl which is set later in the method ImageLoad. And i am trying to set the variable and return it when the method is called
Solution 1:
You can do it as follows:
publicclassImageActions {
publicinterfaceOntaskCompleted{
voidonSuccess(Uri returnurl);
voidonfail();
}
private Uri downloadUrl;
publicvoidImageLoad(final OntaskCompleted listener)
{
FirebaseStoragestorage= FirebaseStorage.getInstance();
StorageReferencestorageRef= storage.getReferenceFromUrl("gs://apptest.appspot.com");
Urifile= Uri.fromFile(newFile("sdcard/DCIM/Camera/1466831822883.jpg"));
StorageMetadatametadata=newStorageMetadata.Builder().setContentType("image/jpeg").build();
UploadTaskuploadTask= storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);
uploadTask.addOnProgressListener(newOnProgressListener<UploadTask.TaskSnapshot>() {
@OverridepublicvoidonProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnPausedListener(newOnPausedListener<UploadTask.TaskSnapshot>() {
@OverridepublicvoidonPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(newOnFailureListener() {
@OverridepublicvoidonFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
listener.onfail();
}
}).addOnSuccessListener(newOnSuccessListener<UploadTask.TaskSnapshot>() {
@OverridepublicvoidonSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
System.out.println("Upload completed");
listenr.onSuccess(downloadurl)
}
});
}
}
Now call this function as follows:
ImageLoadObject.ImageLoad(new OntaskCompleted(){
@Override
void onSuccess(Uri url){
//Here you will get the url after upload complete
}
@Override
void onFail(){
}
});
Hope this helps you.
Post a Comment for "How To Return A Variable From A Listener Method"