Getting List of Files/Folders


Let's find out how to get a list of folders and files by a specified path. The path doesn't need to be full; for example, instead of passing /storage/emulated/0/DCIM/Camera, you only pass /DCIM/Camera, and this applies EVERYWHERE.

This method will be return a JSONArray, but I changed it to MutableList:

Kotlin

private fun getListOfObjects(ac: Activity, path: String): MutableList<DirectoryContents> {
    val contentResolver: ContentResolver = ac.contentResolver
    val uri = Uri.parse("content://com.anready.croissant.files")
        .buildUpon()
        .appendQueryParameter("path", patb) // Providing path
        appendQueryParameter("command", "list") // Set command to list
        build()

    var cursor: Cursor? = null
    try {
        cursor = contentResolver.query(uri, null, null, null, null)
        if (cursor != null && cursor.moveToFirst()) {
            val dataIndex = cursor.getColumnIndex("response")
            if (dataIndex == -1) {
                println("Data column not found")
                return mutableListOf()
            }

            val jsonArray = JSONArray(cursor.getString(dataIndex))
            if (error(jsonArray)) { //Checking response on error
                println("Error: " + jsonArray.getJSONObject(0).getString("error"))
                return mutableListOf()
            }

            val fullList = mutableListOf<DirectoryContents>()

            for (i in 0 until jsonArray.length()) {
                val fileInfo = jsonArray.getJSONObject(i)
                fullList.add(
                    DirectoryContents(
                        name = fileInfo.getString("name"),
                        isDirectory = fileInfo.getBoolean("type"),
                        isHidden = fileInfo.getBoolean("visibility")
                    )
                )
            }

            return fullList
        } else {
            println("Error while getting data!")
        }
    } catch (e: Exception) {
        println("Error while getting data!\n" + e.message)
    } finally {
        cursor?.close()
    }

    return mutableListOf()
}

private fun error(jsonArray: JSONArray): Boolean { //Method of getting error
    try {
        val error = jsonArray.getJSONObject(0)
        error.getString("error")
        return true
    } catch (e: JSONException) {
        return false
    }
}
// Also in another file with name DirectoryContents put this lines:
class DirectoryContents(val name: String, val isDirectory: Boolean, val isHidden: Boolean)
            

By calling this method: getListOfObjects(this, "/"). It will return MutableList of DirectoryContents, you can receive error code: 02 and 01 (See the article Errors). You can use this List as you wish


That's it! Go to the next page