【问题标题】:Why can't this retieve the download URL of an image on Firebase Storage?为什么这不能检索 Firebase 存储上图像的下载 URL?
【发布时间】:2021-09-15 09:19:53
【问题描述】:

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

//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();

【问题讨论】:

  • 请仅使用android-studio 标签来回答有关 Android Studio IDE 本身的问题。对于一般的 Android 编程问题,请使用android 标签。

标签: android firebase firebase-realtime-database firebase-storage


【解决方案1】:

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();
    }
});

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

【讨论】:

  • 谢谢!我没有意识到它是异步的哈哈。我也感谢您链接其他资源。
猜你喜欢
  • 2020-07-10
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 2018-01-09
  • 2021-01-17
  • 2017-02-23
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多