-2
在下面的代碼中,我聲明瞭稍後在方法ImageLoad中設置的類變量downloadUrl。我試圖設置變量並在調用方法時返回它。但是我看到變量返回null。這裏發生了什麼?我如何正確地返回這個變量?如何從偵聽器方法返回變量
public class ImageActions {
private Uri downloadUrl;
public Uri ImageLoad()
{
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://apptest.appspot.com");
Uri file = Uri.fromFile(new File("sdcard/DCIM/Camera/1466831822883.jpg"));
StorageMetadata metadata = new StorageMetadata.Builder().setContentType("image/jpeg").build();
UploadTask uploadTask = storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
@Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
System.out.println("Upload failed");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
System.out.println("beforeReturn" + downloadUrl); //This prints correct (non-null) value
System.out.println("Upload completed");
}
});
System.out.println("beforeReturn" + downloadUrl); //This prints null
return downloadUrl;
}
}
它將爲空,因爲上傳任務是異步的,並且你得到null的語句在'onSuccess'之前執行,就像在你開始'uploadtask'後執行S.O.P語句一樣。你可以通過自己的界面來返回url,這將是最好的。 –