2019-09-05

How To List Files in Google's Firebase Storage


This is an example of how to list the files stored in a given Storage Bucket (like a "folder") in Java under Android.

Follow Google's description "Get Started with Cloud Storage on Android" in order to configure Firebase Storage for your App.

For the detailed description of listing files (the example listed there uses Kotlin, not Java).

final String LOG_TAG = "MyTag"

// The first step in accessing your storage bucket is to create an instance of FirebaseStorage:
FirebaseStorage storage = FirebaseStorage.getInstance();

// ... or you also can specify a specific storage bucket (see document from the first URL from above)
// FirebaseStorage storage = FirebaseStorage.getInstance("gs://my-custom-bucket");

// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// Create a child reference. The myKindOfFolder now points to the "kind of subdirectory" containing the file(s) to be listed
storageRef.child("myKindOfFolder")
        .listAll()
        .addOnSuccessListener(new OnSuccessListener<ListResult>() {
            @Override
            public void onSuccess(@NonNull ListResult result) {
                Log.d(LOG_TAG, "onSuccess()");
                Iterator<StorageReference> i = result.getItems().iterator();
                StorageReference ref;
                while (i.hasNext()) {
                    ref = i.next();
                    Log.d(LOG_TAG, "onSuccess() File name: " + ref.getName());
                }
            }
        })
.addOnFailureListener(new OnFailureListener() {
    public void onFailure(@NonNull Exception e) {
        Log.er(LOG_TAG, "onFailure(): ", e);
    }
});

Output
. . .
. . . onSuccess() File name: File01.txt
. . . onSuccess() File name: File02.txt
. . . onSuccess() File name: File03.txt
. . .