Firebase getDownloadUrl无法执行onSuccess或onFailure

时间:2019-04-02 07:18:56

标签: java android firebase google-cloud-storage

我正在尝试在Cloud Storage中获取音频文件的URL。我可以将其发布到存储中,但是此函数仅返回null。调试时,它会同时跳过onSuccessonFailure

我知道filename变量是正确的,但也尝试对其进行硬编码,但未成功。我将mStorageRef传递为StorageReference。 fileUrl当前是一个全局字符串。

mStorageRef = FirebaseStorage.getInstance().getReference();

String getFileUrl(String filename, StorageReference storageRef) {

        storageRef.child("music").child(filename).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                fileUrl = uri.toString();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                fileUrl = e.getMessage();
            }
        });

        return fileUrl;
    }

这些文件位于称为音乐的顶级文件夹中。

firebase storage structure

1 个答案:

答案 0 :(得分:1)

  

我可以很好地发布到存储中,但是此函数只返回null。

您现在无法返回尚未加载的内容。换句话说,您不能简单地将fileUrl变量创建为全局变量并在onSuccess()方法之外使用它,因为由于该方法的异步行为,它将始终为null。这意味着,当您尝试在该方法之外使用该结果时,数据尚未从数据库中加载完毕,因此无法访问。

对此问题的快速解决方案是仅在fileUrl方法内部使用来自数据库的onSuccess()的值,否则我建议您从此查看anwser的最后一部分 post ,其中我解释了如何使用自定义回调来完成。您也可以查看此 video 以获得更好的理解。

还请确保用户设备上的互联网连接稳定。

相关问题