Search code examples
androidandroid-contentresolver

ContentResolver Query on DocumentContract Lists all files disregarding selection


Im trying to get all files from a directory which have a certain MIME Type - i want all images.

I had used some example code where you use MediaStore as URI but it later turned out difficult to filter that for the chosen directory because the URIs returned in the resultset have a different format than the URI i supplied...

So instead i found this example code https://github.com/googlesamples/android-DirectorySelection

it queries the DocumentContract on the selected subtree and now needs filtering for the desired MIME Type.

the problem is: no matter what i supply as selection argument it will always list all files/directories found in that directory.

i even tried "1=2" as selection and this still listed everything. any ideas what im doing wrong??

val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( uri, DocumentsContract.getTreeDocumentId(uri) )

        val childCursor = contentResolver.query(
            childrenUri,
            arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME, COLUMN_MIME_TYPE),
            "$COLUMN_MIME_TYPE=?",
            Array(1){MimeTypeMap.getSingleton().getExtensionFromMimeType("jpg")},
            null
        )
        Log.i("ADDFOLDER", "files: ${childCursor.count}")
        try {
            while (childCursor.moveToNext()) {
                Log.d(
                    TAG, "found child=" + childCursor.getString(0) + ", mime=" + childCursor
                        .getString(1)
                )
            }
        } finally {
            closeQuietly(childCursor)
        }

Solution

  • FileSystemProvider doesn't support selection or sort args for children, it's broken.

    https://github.com/aosp-mirror/platform_frameworks_base/blob/53a9ccaa926945149b4546c67b50ce1ae88ba777/core/java/com/android/internal/content/FileSystemProvider.java#L285

    The base DocumentsProvider strips the selection args for a children query as well, so I wouldn't rely on it ever working. You could use the search documents Uri, which does do filtering, but still ignores the sort order (Edit: and more importantly, is a recursive search, so it'll search within any subfolders.)*

    *From: https://www.reddit.com/r/androiddev/comments/b80qqt/weekly_questions_thread_april_01_2019/ek9oew6/