Algorithm to scan all files in android

I am trying to make an algorithm to scan all files in android but I am facing issues in adding directories to an array can anyone tell me why I am facing this issue?

The code I have currently written:

private fun getFiles() {
val mainDirectory = File(“storage/emulated/0/”)
val files = mainDirectory.listFiles()
val fileDirectories = Array(999){File("")}
var count = 0
if (files != null) {
for (file in files) {
if (file.name.endsWith(".mp3") ||
file.name.endsWith(".MP3") ||
file.name.endsWith(".M4A") ||
file.name.endsWith(".m4a") ||
file.name.endsWith(".AAC") ||
file.name.endsWith(".aac")) {
databaseHandler.addSong(file.name, file.path, file.toURI())
} else if (file.isDirectory) {
fileDirectories[count] = file
count++
}
}
}
}

use a list instead (i.e. listOf(File("")) and then do if(file.name.blablabla) { //something } else if (file.isDirectory) { fileDirectories.append(file) }
Note that you also won’t need the count variable anymore.

Thank you,
if you need any help contact me on Instagram at ashique_bava