How can I create an Android file list?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By BielMT

I wanted to create a file explorer for my game but I couldn’t find how to do it and filedialog doesn’t work on android.

:bust_in_silhouette: Reply From: Wakatta

It’s weird allot of users say filedialog does not work on Android and there’s even a bug tracker for it but it works perfectly fine for my purposes.

You can use File, Directory and GridContainer node to mimic a file explorer

Know that the entire Android file system is not accessible unless rooted
And you should do a check for external storage first
Also ensure your storage permissions are enabled

How to create an Android file list

func get_files(path):
    var _files = Array()
    var dir = Directory.new()
    if dir.open(path) == OK:
        dir.list_dir_begin(true, true)
        var file_name = dir.get_next()
        while file_name != "":
            if not dir.current_is_dir():
                var _file = Dictionary()
                _file.name = file_name
                _file.path = path + "/" + file_name
                #_file.size = todo
                _files.append(_file)
            file_name = dir.get_next()
    else:
        push_error("error")

func _ready():
    var file_list = get_files("/sdcard")

The above code snippet will give you a list of file names only and not the folders
Then you can do something like

var file = File.new()
file.open(file_list[0].path)

Wakatta | 2021-06-16 21:36