diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt index a21f897fe..d4027984f 100644 --- a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt +++ b/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt @@ -49,13 +49,36 @@ fun Context.launchSettings() { startActivity(Intent(this, SettingsActivity::class.java)) } +fun Context.getMediaFolders(): Set { + val uri = MediaStore.Files.getContentUri("external") + val where = "${MediaStore.Files.FileColumns.MEDIA_TYPE} = ? OR ${MediaStore.Files.FileColumns.MEDIA_TYPE} = ?" + val args = arrayOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE.toString(), MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO.toString()) + val columns = arrayOf(MediaStore.Files.FileColumns.PARENT, MediaStore.Images.Media.DATA) + val parentsSet = HashSet() + + var cursor: Cursor? = null + try { + cursor = contentResolver.query(uri, columns, where, args, null) + if (cursor?.moveToFirst() == true) { + do { + val curPath = cursor.getStringValue(MediaStore.Images.Media.DATA) ?: "" + parentsSet.add(File(curPath).parent) + } while (cursor.moveToNext()) + } + } finally { + cursor?.close() + } + + return parentsSet +} + fun Context.getParents(): ArrayList { val uri = MediaStore.Files.getContentUri("external") val columns = arrayOf(MediaStore.Images.Media.DATA) - var cursor: Cursor? = null val parents = ArrayList() - val parentsSet = HashSet() + + var cursor: Cursor? = null try { cursor = contentResolver.query(uri, columns, null, null, null) if (cursor?.moveToFirst() == true) { @@ -69,13 +92,15 @@ fun Context.getParents(): ArrayList { cursor?.close() } - parentsSet.filterTo(parents, { hasImageVideoGif(File(it)) }) + val mediaFolders = getMediaFolders() + parentsSet.filterTo(parents, { mediaFolders.contains(it) || hasImageVideoGif(File(it)) }) if (config.showHiddenFolders) { parents.addAll(getNoMediaFolders()) } else { removeNoMediaFolders(parents) } + return parents } @@ -123,7 +148,8 @@ fun Context.getNoMediaFolders(): ArrayList { fun hasImageVideoGif(dir: File): Boolean { if (dir.isDirectory) { - dir.listFiles()?.filter(File::isImageVideoGif)?.any { return true } + val files = dir.listFiles() ?: return false + files.filter(File::isImageVideoGif).any { return true } } return false }