From 513694c117aba6e4fd41a7267a6f21b8c0dd1161 Mon Sep 17 00:00:00 2001 From: tibbi Date: Fri, 24 Feb 2017 22:02:09 +0100 Subject: [PATCH] add a helper function for fast getting folders with media --- .../gallery/extensions/context.kt | 34 ++++++++++++++++--- 1 file changed, 30 insertions(+), 4 deletions(-) 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 }