为什么这不能获取 Firebase 存储上图像的下载 URL?

Why can't this retieve the download URL of an image on Firebase Storage?

我正在尝试通过在我用来上传的 putImage 调用的 onSuccessListener 中获取我想要检索的图像的下载 url 来从 android 应用程序的 firebase 存储中检索图像首先是图像。我将下载 URL 保存在一个字段变量中,但问题是该字段变量没有更新。在我尝试将 url 字段变量的值设置为等于我要检索的图像的下载 URl 之后,我使用 toast 打印出它的值,但它保持不变。我不确定为什么会这样,所以如果能帮我解决这个问题,我将不胜感激。

//field variable that s meant to hold download url for the image I want to retrieve
String url = "never changed"

...

final String imageKey = UUID.randomUUID().toString();
        StorageReference profileref = storageReference.child("contactProfiles/" + imageKey);
        profileref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                task.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        //setting url equal to url of the image I want to retrieve 
                        url = uri.toString();
                    }
                });
                Toast.makeText(ContactCreation.this, "Successful Profile Picture Upload", Toast.LENGTH_SHORT).show();
            }
        })
         .addOnFailureListener(new OnFailureListener() {
             @Override
             public void onFailure(@NonNull Exception e) {
                 Toast.makeText(ContactCreation.this, "Failed to Upload Profile Picture", Toast.LENGTH_SHORT).show();
             }
         });

  //Seeing if the url changed or not
        Toast.makeText(ContactCreation.this, url, Toast.LENGTH_SHORT).show();

getDownloadURL的调用是对服务器的调用,因此是异步执行的。这意味着现在在您的代码中,Toast.makeText(ContactCreation.this, urlurl = uri.toString() 运行之前运行,这解释了为什么它不记录任何值。

解决方案始终相同:任何需要该值的代码都需要在使用该值调用的 onSuccess 内部,或者需要从那里调用。

所以:

task.addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        url = uri.toString();
        Toast.makeText(ContactCreation.this, url, Toast.LENGTH_SHORT).show();
    }
});

如果您不熟悉这种异步行为,我建议您阅读更多相关内容。例如:

  • ,显示了 Task 听众的一些链接。
  • How to get the download url from Firebase Storage?
  • Hello, I have problem to upload my image to my firebase storage