我正在尝试获取云存储中音频文件的 URL
。我可以很好地发布到存储,但这个函数只返回 null。调试时,它会跳过 onSuccess
和 onFailure
。
我知道文件名变量是正确的,但也尝试过对其进行硬编码但没有成功。我正在将 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 的顶级文件夹中。
最佳答案
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/