java - Firebase getDownloadUrl 不执行 onSuccess 或 onFailure

标签 java android firebase google-cloud-storage

我正在尝试获取云存储中音频文件的 URL。我可以很好地发布到存储,但这个函数只返回 null。调试时,它会跳过 onSuccessonFailure

我知道文件名变量是正确的,但也尝试过对其进行硬编码但没有成功。我正在将 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;
    }

这些文件位于名为 music 的顶级文件夹中。

firebase storage structure

最佳答案

I can post to the storage just fine, but this function only returns null.

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

一个快速解决这个问题的方法是在 onSuccess() 方法中使用来自数据库的 fileUrl 的值,否则我建议你看我的答案的最后一部分来自 post 我在其中解释了如何使用自定义回调来完成。你也可以看看这个 video 以便更好地理解。

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

关于java - Firebase getDownloadUrl 不执行 onSuccess 或 onFailure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55469007/

相关文章:

java - JSoup 从 img 类中提取标题

java - MapBox:在前台服务中初始化 LocationEngineCallback

android - 邀请 friend 使用 Facebook 应用程序 - android,未发送邀请

java - 在显示最小化的 SWT 中隐藏 ON_TOP shell

java - java无限循环

android - android中具有相同分辨率但屏幕尺寸不同的设备的布局

java - 如何使用 hashmap 通过数据库检索不同 editText 的值

android - 将多张图片上传到 firebase 存储

javascript - Firebase 托管 - 从未经身份验证的来源加载脚本

javascript - 使用 Cloud Firestore 获取有关实时更新的先前数据