简体   繁体   中英

Firebase getDownloadUrl doesn't execute onSuccess or onFailure

I'm trying to get the URL of an audio file in Cloud Storage. I can post to the storage just fine, but this function only returns null. When debugging it hops over both onSuccess and onFailure .

I know the filename variable is correct, but have tried hardcoding it as well with no success. I'm passing mStorageRef in as the StorageReference . fileUrl is currently a global string.

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

The files are within a top-level folder called music.

Firebase 存储结构

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

You cannot return something now, that hasn't been loaded yet. With other words, you cannot simply create the fileUrl variable as a global variable and use it outside the onSuccess() method because it will always be null due the asynchronous behaviour of this method. This means that by the time you are trying to use that result outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.

A quick solve for this problem would be to use the value of fileUrl that is coming from the database only inside the onSuccess() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Be also sure to have a stable internet connection on user's device.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM