├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── menu
│ │ │ │ └── menu_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── layout
│ │ │ │ ├── file_list_item.xml
│ │ │ │ └── activity_main.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── jaiselrahman
│ │ │ └── filepickersample
│ │ │ ├── FileListAdapter.java
│ │ │ └── MainActivity.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── jaiselrahman
│ │ │ └── filepickersample
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── jaiselrahman
│ │ └── filepickersample
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── filepicker
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── xml
│ │ │ │ └── com_jaiselrahman_filepicker_provider_paths.xml
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── dimens.xml
│ │ │ ├── drawable
│ │ │ │ ├── ic_selected.xml
│ │ │ │ ├── ic_file.xml
│ │ │ │ ├── ic_audio.xml
│ │ │ │ ├── transparent_background.xml
│ │ │ │ ├── ic_dir.xml
│ │ │ │ ├── ic_videocam.xml
│ │ │ │ └── ic_camera.xml
│ │ │ ├── menu
│ │ │ │ └── filegallery_menu.xml
│ │ │ └── layout
│ │ │ │ ├── filepicker_gallery.xml
│ │ │ │ ├── filegallery_item.xml
│ │ │ │ └── filepicker_dir_item.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── jaiselrahman
│ │ │ └── filepicker
│ │ │ ├── view
│ │ │ ├── DividerItemDecoration.java
│ │ │ └── SquareImage.java
│ │ │ ├── utils
│ │ │ ├── FilePickerProvider.java
│ │ │ ├── TimeUtils.java
│ │ │ └── FileUtils.java
│ │ │ ├── activity
│ │ │ ├── PickFile.java
│ │ │ └── DirSelectActivity.java
│ │ │ ├── model
│ │ │ ├── Dir.java
│ │ │ ├── DirViewModel.java
│ │ │ ├── MediaFileViewModel.java
│ │ │ ├── DirLoader.java
│ │ │ ├── MediaFile.java
│ │ │ ├── MediaFileLoader.java
│ │ │ ├── DirDataSource.java
│ │ │ └── MediaFileDataSource.java
│ │ │ ├── adapter
│ │ │ ├── DirListAdapter.java
│ │ │ ├── MultiSelectionAdapter.java
│ │ │ └── FileGalleryAdapter.java
│ │ │ └── config
│ │ │ └── Configurations.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── jaiselrahman
│ │ │ └── filepicker
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── jaiselrahman
│ │ └── filepicker
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── pics
├── pic.gif
├── pic_1.png
├── pic_2.png
├── pic_3.png
└── pic_4.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── .github
├── ISSUE_TEMPLATE
│ ├── feature_request.md
│ └── bug_report.md
├── FUNDING.yml
└── PULL_REQUEST_TEMPLATE.md
├── gradle.properties
├── gradlew.bat
├── gradlew
├── README.md
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/filepicker/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':filepicker'
2 |
--------------------------------------------------------------------------------
/pics/pic.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/pics/pic.gif
--------------------------------------------------------------------------------
/pics/pic_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/pics/pic_1.png
--------------------------------------------------------------------------------
/pics/pic_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/pics/pic_2.png
--------------------------------------------------------------------------------
/pics/pic_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/pics/pic_3.png
--------------------------------------------------------------------------------
/pics/pic_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/pics/pic_4.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | gradle.properties
4 | /local.properties
5 | /.idea
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaiselrahman/FilePicker/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/filepicker/src/main/res/xml/com_jaiselrahman_filepicker_provider_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jun 10 13:16:39 IST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 | #80000000
7 | #1c1c1c
8 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/ic_selected.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/ic_file.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/ic_audio.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/transparent_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
11 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/ic_dir.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | FilePicker
3 | File Thumbnail
4 | Open Camera
5 | Done
6 | %3$s (%1$d/%2$d)
7 | %1$d/%2$d
8 | Permission not given
9 |
10 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/ic_videocam.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/filepicker/src/test/java/com/jaiselrahman/filepicker/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.jaiselrahman.filepicker;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/jaiselrahman/filepickersample/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.jaiselrahman.filepickersample;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem? Please describe.**
8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
9 |
10 | **Describe the solution you'd like**
11 | A clear and concise description of what you want to happen.
12 |
13 | **Describe alternatives you've considered**
14 | A clear and concise description of any alternative solutions or features you've considered.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 |
5 | ---
6 |
7 | **Describe the bug**
8 | A clear and concise description of what the bug is.
9 |
10 | **To Reproduce**
11 | Steps to reproduce the behavior:
12 | 1.
13 | 2.
14 | 3.
15 | 4.
16 |
17 | **Expected behavior**
18 | A clear and concise description of what you expected to happen.
19 |
20 | **Screenshots**
21 | If applicable, add screenshots to help explain your problem.
22 |
23 | **Android info (please complete the following information):**
24 | - Device/Emulator
25 | - API level
26 |
27 | **Additional context**
28 | Add any other context about the problem here.
29 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: jaiselrahman
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: ['https://paypal.me/jaiselrahman', 'https://www.buymeacoffee.com/jaiselrahman']
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | FilePicker
3 | Launch File Picker
4 | File thumbnail
5 | Uri : %1$s
6 | Size : %1$d
7 | Mime: %1$s
8 | Type : %1$d
9 | Name : %1$s
10 | BucketName : %1$s
11 | Launch audio picker
12 | Launch video picker
13 | Launch image picker
14 | Share Log
15 |
16 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/drawable/ic_camera.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | android.enableJetifier=true
10 | android.useAndroidX=true
11 | org.gradle.jvmargs=-Xmx1536m
12 | # When configured, Gradle will run in incubating parallel mode.
13 | # This option should only be used with decoupled projects. More details, visit
14 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
15 | # org.gradle.parallel=true
16 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | 2dp
20 |
--------------------------------------------------------------------------------
/filepicker/src/androidTest/java/com/jaiselrahman/filepicker/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.jaiselrahman.filepicker;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.InstrumentationRegistry;
6 | import androidx.test.runner.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.assertEquals;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getTargetContext();
24 |
25 | assertEquals("com.jaisel.filepicker.test", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/jaiselrahman/filepickersample/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.jaiselrahman.filepickersample;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.InstrumentationRegistry;
6 | import androidx.test.runner.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.assertEquals;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getTargetContext();
24 |
25 | assertEquals("com.jaiselrahman.filepickersample", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/menu/filegallery_menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
--------------------------------------------------------------------------------
/filepicker/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
13 |
16 |
17 |
18 |
21 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
--------------------------------------------------------------------------------
/filepicker/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
23 | -keep public class * implements com.bumptech.glide.module.GlideModule
24 | -keep public class * extends com.bumptech.glide.module.AppGlideModule
25 | -keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
26 | **[] $VALUES;
27 | public *;
28 | }
29 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/view/DividerItemDecoration.java:
--------------------------------------------------------------------------------
1 | package com.jaiselrahman.filepicker.view;
2 |
3 | import android.graphics.Rect;
4 | import android.view.View;
5 |
6 | import androidx.recyclerview.widget.RecyclerView;
7 |
8 | public class DividerItemDecoration extends RecyclerView.ItemDecoration {
9 | private int spacing;
10 | private int spanCount;
11 |
12 | public DividerItemDecoration(int spacing, int spanCount) {
13 | this.spacing = spacing;
14 | this.spanCount = spanCount;
15 | }
16 |
17 | @Override
18 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
19 | RecyclerView.State state) {
20 | int position = parent.getChildAdapterPosition(view); // item position
21 | int column = position % spanCount; // item column
22 |
23 | outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
24 | outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
25 | if (position >= spanCount) {
26 | outRect.top = spacing; // item top
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/filepicker/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 29
5 | buildToolsVersion '29.0.2'
6 | defaultConfig {
7 | minSdkVersion 14
8 | targetSdkVersion 29
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
12 | vectorDrawables.useSupportLibrary = true
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | implementation fileTree(include: ['*.jar'], dir: 'libs')
25 | implementation 'com.google.android.material:material:1.1.0'
26 | implementation 'androidx.recyclerview:recyclerview:1.1.0'
27 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
28 |
29 | implementation 'androidx.paging:paging-runtime:2.1.2'
30 |
31 | implementation 'com.github.bumptech.glide:glide:4.10.0'
32 |
33 | implementation "androidx.activity:activity:1.2.0-alpha04"
34 |
35 | testImplementation 'junit:junit:4.12'
36 | androidTestImplementation 'androidx.test:runner:1.1.2-alpha01'
37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.2-alpha01'
38 | }
39 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ## Description
6 |
7 |
8 | ## Motivation and Context
9 |
10 |
11 |
12 | ## How Has This Been Tested?
13 |
14 |
15 |
16 |
17 | ## Screenshots (if appropriate):
18 |
19 | ## Types of changes
20 |
21 | - [ ] Bug fix (non-breaking change which fixes an issue)
22 | - [ ] New feature (non-breaking change which adds functionality)
23 | - [ ] Breaking change (fix or feature that would cause existing functionality to change)
24 |
25 | ## Checklist:
26 |
27 |
28 | - [ ] My code follows the code style of this project.
29 | - [ ] My change requires a change to the documentation.
30 | - [ ] I have updated the documentation accordingly.
31 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/utils/FilePickerProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.utils;
18 |
19 | import android.content.Context;
20 | import android.net.Uri;
21 |
22 | import androidx.annotation.NonNull;
23 | import androidx.core.content.FileProvider;
24 |
25 | import java.io.File;
26 |
27 | public class FilePickerProvider extends FileProvider {
28 | private static final String FILE_PROVIDER = ".filepicker.provider";
29 |
30 | public static String getAuthority(@NonNull Context context) {
31 | return context.getPackageName() + FILE_PROVIDER;
32 | }
33 |
34 | public static Uri getUriForFile(@NonNull Context context, @NonNull File file) {
35 | return getUriForFile(context, getAuthority(context), file);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/view/SquareImage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.view;
18 |
19 | import android.content.Context;
20 | import android.util.AttributeSet;
21 |
22 | import androidx.appcompat.widget.AppCompatImageView;
23 |
24 | public class SquareImage extends AppCompatImageView {
25 | public SquareImage(Context context) {
26 | this(context, null);
27 | }
28 |
29 | public SquareImage(Context context, AttributeSet attrs) {
30 | this(context, attrs, 0);
31 | }
32 |
33 | public SquareImage(Context context, AttributeSet attrs, int defStyle) {
34 | super(context, attrs, defStyle);
35 | }
36 |
37 | @Override
38 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
39 | setMeasuredDimension(widthMeasureSpec, widthMeasureSpec);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/utils/TimeUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.utils;
18 |
19 | import java.util.concurrent.TimeUnit;
20 |
21 | public class TimeUtils {
22 | public static String getDuration(long duration) {
23 | long hours = TimeUnit.MILLISECONDS.toHours(duration);
24 | duration -= TimeUnit.HOURS.toMillis(hours);
25 | long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
26 | duration -= TimeUnit.MINUTES.toMillis(minutes);
27 | long seconds = TimeUnit.MILLISECONDS.toSeconds(duration);
28 | StringBuilder durationBuilder = new StringBuilder();
29 | if (hours > 0) {
30 | durationBuilder.append(hours)
31 | .append(":");
32 | }
33 | if (minutes < 10)
34 | durationBuilder.append('0');
35 | durationBuilder.append(minutes)
36 | .append(":");
37 | if (seconds < 10)
38 | durationBuilder.append('0');
39 | durationBuilder.append(seconds);
40 | return durationBuilder.toString();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | signingConfigs {
5 | config {
6 | Properties properties = new Properties()
7 | File propertiesFile = project.rootProject.file('app/gradle.properties')
8 | if (propertiesFile.exists()) {
9 | properties.load(propertiesFile.newDataInputStream())
10 | storeFile file(properties.getProperty('KEYSTORE_FILE'))
11 | keyAlias properties.getProperty('KEY_ALIAS')
12 | storePassword properties.getProperty('KEYSTORE_PASSWORD')
13 | keyPassword properties.getProperty('KEY_PASSWORD')
14 | }
15 | }
16 | }
17 | buildToolsVersion '29.0.2'
18 | compileSdkVersion 29
19 | defaultConfig {
20 | applicationId "com.jaiselrahman.filepickersample"
21 | minSdkVersion 14
22 | targetSdkVersion 29
23 | versionCode 1
24 | versionName "1.0"
25 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
26 | }
27 | buildTypes {
28 | release {
29 | minifyEnabled false
30 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
31 | signingConfig signingConfigs.config
32 | }
33 | }
34 | }
35 |
36 | dependencies {
37 | implementation fileTree(include: ['*.jar'], dir: 'libs')
38 | implementation 'androidx.appcompat:appcompat:1.1.0'
39 | implementation 'androidx.annotation:annotation:1.1.0'
40 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
41 | implementation 'androidx.recyclerview:recyclerview:1.1.0'
42 | implementation 'com.github.bumptech.glide:glide:4.10.0'
43 | testImplementation 'junit:junit:4.12'
44 | androidTestImplementation 'androidx.test:runner:1.1.2-alpha01'
45 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.2-alpha01'
46 | implementation project(':filepicker')
47 | }
48 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/layout/filepicker_gallery.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
23 |
24 |
30 |
31 |
35 |
36 |
37 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/activity/PickFile.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.activity;
18 |
19 | import android.content.Context;
20 | import android.content.Intent;
21 |
22 | import androidx.activity.result.contract.ActivityResultContract;
23 | import androidx.annotation.NonNull;
24 | import androidx.annotation.Nullable;
25 |
26 | import com.jaiselrahman.filepicker.config.Configurations;
27 | import com.jaiselrahman.filepicker.model.MediaFile;
28 |
29 | import java.util.List;
30 |
31 | import static android.app.Activity.RESULT_OK;
32 |
33 | public class PickFile extends ActivityResultContract> {
34 | private boolean throughDir = false;
35 |
36 | @NonNull
37 | @Override
38 | public Intent createIntent(@NonNull Context context, Configurations input) {
39 | return new Intent(context,
40 | throughDir ? DirSelectActivity.class : FilePickerActivity.class
41 | ).putExtra(FilePickerActivity.CONFIGS, input);
42 | }
43 |
44 | @Override
45 | public List parseResult(int resultCode, @Nullable Intent intent) {
46 | if (resultCode == RESULT_OK && intent != null) {
47 | return intent.getParcelableArrayListExtra(FilePickerActivity.MEDIA_FILES);
48 | }
49 | return null;
50 | }
51 |
52 | public PickFile throughDir(boolean throughDir) {
53 | this.throughDir = throughDir;
54 | return this;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/Dir.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.net.Uri;
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 |
23 | public class Dir implements Parcelable {
24 | private long id;
25 | private String name;
26 | private Uri preview;
27 | private int count;
28 |
29 | public Dir() {
30 | }
31 |
32 | protected Dir(Parcel in) {
33 | id = in.readLong();
34 | name = in.readString();
35 | preview = in.readParcelable(Uri.class.getClassLoader());
36 | count = in.readInt();
37 | }
38 |
39 | public void setId(long id) {
40 | this.id = id;
41 | }
42 |
43 | public long getId() {
44 | return id;
45 | }
46 |
47 | public void setCount(int count) {
48 | this.count = count;
49 | }
50 |
51 | public int getCount() {
52 | return count;
53 | }
54 |
55 | public void setName(String name) {
56 | this.name = name;
57 | }
58 |
59 | public String getName() {
60 | return name;
61 | }
62 |
63 | public void setPreview(Uri preview) {
64 | this.preview = preview;
65 | }
66 |
67 | public Uri getPreview() {
68 | return preview;
69 | }
70 |
71 | public static final Creator CREATOR = new Creator() {
72 | @Override
73 | public Dir createFromParcel(Parcel in) {
74 | return new Dir(in);
75 | }
76 |
77 | @Override
78 | public Dir[] newArray(int size) {
79 | return new Dir[size];
80 | }
81 | };
82 |
83 | @Override
84 | public int describeContents() {
85 | return 0;
86 | }
87 |
88 | @Override
89 | public void writeToParcel(Parcel dest, int flags) {
90 | dest.writeLong(id);
91 | dest.writeString(name);
92 | dest.writeParcelable(preview, flags);
93 | dest.writeInt(count);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/utils/FileUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2019, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.utils;
18 |
19 | import android.provider.MediaStore;
20 |
21 | import com.jaiselrahman.filepicker.config.Configurations;
22 |
23 | import java.io.File;
24 | import java.util.regex.Matcher;
25 |
26 | import static java.io.File.separatorChar;
27 |
28 | public class FileUtils {
29 | public static boolean toIgnoreFolder(String path, Configurations configs) {
30 | String parent = getParent(path);
31 | if (configs.isIgnoreHiddenFile() && getName(parent).startsWith(".")) return true;
32 | if (configs.getIgnorePathMatchers() != null) {
33 | for (Matcher matcher : configs.getIgnorePathMatchers()) {
34 | if (matcher.reset(path).matches()) {
35 | return true;
36 | }
37 | }
38 | }
39 | if (configs.isIgnoreNoMediaDir()) {
40 | while (!parent.isEmpty() && !new File(parent, MediaStore.MEDIA_IGNORE_FILENAME).exists()) {
41 | parent = getParent(parent);
42 | }
43 | return !parent.isEmpty();
44 | }
45 | return false;
46 | }
47 |
48 | public static String getParent(String path) {
49 | int index = path.lastIndexOf(separatorChar);
50 | int prefixLength = getPrefixLength(path);
51 | if (index < prefixLength) {
52 | if ((prefixLength > 0) && (path.length() > prefixLength))
53 | return path.substring(0, prefixLength);
54 | return "";
55 | }
56 | return path.substring(0, index);
57 | }
58 |
59 | private static String getName(String path) {
60 | int index = path.lastIndexOf(separatorChar);
61 | int prefixLength = getPrefixLength(path);
62 | if (index < prefixLength) return path.substring(prefixLength);
63 | return path.substring(index + 1);
64 | }
65 |
66 | private static int getPrefixLength(String path) {
67 | return path.length() == 0 ? 0 : (path.charAt(0) == '/' ? 1 : 0);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/DirViewModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.content.ContentResolver;
20 |
21 | import androidx.annotation.NonNull;
22 | import androidx.lifecycle.LiveData;
23 | import androidx.lifecycle.ViewModel;
24 | import androidx.lifecycle.ViewModelProvider;
25 | import androidx.paging.LivePagedListBuilder;
26 | import androidx.paging.PagedList;
27 |
28 | import com.jaiselrahman.filepicker.config.Configurations;
29 |
30 | public class DirViewModel extends ViewModel {
31 | public LiveData> dirs;
32 |
33 | private DirViewModel(ContentResolver contentResolver, Configurations configs) {
34 | DirDataSource.Factory dirDataSourceFactory = new DirDataSource.Factory(contentResolver, configs);
35 |
36 | dirs = new LivePagedListBuilder<>(
37 | dirDataSourceFactory,
38 | new PagedList.Config.Builder()
39 | .setPageSize(Configurations.PAGE_SIZE)
40 | .setInitialLoadSizeHint(15)
41 | .setMaxSize(Configurations.PAGE_SIZE * 3)
42 | .setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
43 | .setEnablePlaceholders(false)
44 | .build()
45 | ).build();
46 | }
47 |
48 | public void refresh() {
49 | if (dirs.getValue() != null)
50 | dirs.getValue().getDataSource().invalidate();
51 | }
52 |
53 | public static class Factory extends ViewModelProvider.NewInstanceFactory {
54 | private ContentResolver contentResolver;
55 | private Configurations configs;
56 |
57 | public Factory(ContentResolver contentResolver, Configurations configs) {
58 | this.contentResolver = contentResolver;
59 | this.configs = configs;
60 | }
61 |
62 | @NonNull
63 | @Override
64 | @SuppressWarnings("unchecked")
65 | public T create(@NonNull Class modelClass) {
66 | return (T) new DirViewModel(contentResolver, configs);
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/file_list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
23 |
24 |
32 |
33 |
40 |
41 |
51 |
52 |
61 |
62 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/layout/filegallery_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
25 |
26 |
33 |
34 |
43 |
44 |
56 |
57 |
64 |
65 |
74 |
75 |
84 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
26 |
27 |
36 |
37 |
46 |
47 |
56 |
57 |
66 |
67 |
75 |
76 |
--------------------------------------------------------------------------------
/filepicker/src/main/res/layout/filepicker_dir_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
25 |
26 |
33 |
34 |
40 |
41 |
54 |
55 |
65 |
66 |
67 |
76 |
77 |
86 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/MediaFileViewModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.content.ContentResolver;
20 | import android.database.ContentObserver;
21 |
22 | import androidx.annotation.NonNull;
23 | import androidx.lifecycle.LiveData;
24 | import androidx.lifecycle.ViewModel;
25 | import androidx.lifecycle.ViewModelProvider;
26 | import androidx.paging.LivePagedListBuilder;
27 | import androidx.paging.PagedList;
28 |
29 | import com.jaiselrahman.filepicker.config.Configurations;
30 |
31 | public class MediaFileViewModel extends ViewModel {
32 | private ContentResolver contentResolver;
33 | public LiveData> mediaFiles;
34 |
35 | private ContentObserver contentObserver = new ContentObserver(null) {
36 | @Override
37 | public void onChange(boolean selfChange) {
38 | refresh();
39 | }
40 | };
41 |
42 | private MediaFileViewModel(ContentResolver contentResolver, Configurations configs, Long dirId) {
43 | this.contentResolver = contentResolver;
44 |
45 | MediaFileDataSource.Factory mediaFileDataSourceFactory = new MediaFileDataSource.Factory(contentResolver, configs, dirId);
46 |
47 | mediaFiles = new LivePagedListBuilder<>(
48 | mediaFileDataSourceFactory,
49 | new PagedList.Config.Builder()
50 | .setPageSize(Configurations.PAGE_SIZE)
51 | .setInitialLoadSizeHint(15)
52 | .setMaxSize(Configurations.PAGE_SIZE * 3)
53 | .setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
54 | .setEnablePlaceholders(false)
55 | .build()
56 | ).build();
57 |
58 | contentResolver.registerContentObserver(mediaFileDataSourceFactory.getUri(), true, contentObserver);
59 | }
60 |
61 | @Override
62 | protected void onCleared() {
63 | contentResolver.unregisterContentObserver(contentObserver);
64 | }
65 |
66 | public void refresh() {
67 | if (mediaFiles.getValue() != null)
68 | mediaFiles.getValue().getDataSource().invalidate();
69 | }
70 |
71 | public static class Factory extends ViewModelProvider.NewInstanceFactory {
72 | private ContentResolver contentResolver;
73 | private Configurations configs;
74 | private Long dirId;
75 |
76 | public Factory(ContentResolver contentResolver, Configurations configs, Long dirId) {
77 | this.contentResolver = contentResolver;
78 | this.configs = configs;
79 | this.dirId = dirId;
80 | }
81 |
82 | @NonNull
83 | @Override
84 | @SuppressWarnings("unchecked")
85 | public T create(@NonNull Class modelClass) {
86 | return (T) new MediaFileViewModel(contentResolver, configs, dirId);
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/jaiselrahman/filepickersample/FileListAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepickersample;
18 |
19 | import android.content.Context;
20 | import android.view.LayoutInflater;
21 | import android.view.View;
22 | import android.view.ViewGroup;
23 | import android.widget.ImageView;
24 | import android.widget.TextView;
25 |
26 | import androidx.annotation.NonNull;
27 | import androidx.recyclerview.widget.RecyclerView;
28 |
29 | import com.bumptech.glide.Glide;
30 | import com.jaiselrahman.filepicker.model.MediaFile;
31 |
32 | import java.util.ArrayList;
33 |
34 | public class FileListAdapter extends RecyclerView.Adapter {
35 | private ArrayList mediaFiles;
36 |
37 | public FileListAdapter(ArrayList mediaFiles) {
38 | this.mediaFiles = mediaFiles;
39 | }
40 |
41 | @NonNull
42 | @Override
43 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
44 | View v = LayoutInflater.from(parent.getContext())
45 | .inflate(R.layout.file_list_item, parent, false);
46 | return new ViewHolder(v);
47 | }
48 |
49 | @Override
50 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
51 | MediaFile mediaFile = mediaFiles.get(position);
52 | Context context = holder.itemView.getContext();
53 | holder.filePath.setText(context.getString(R.string.uri, mediaFile.getUri()));
54 | holder.fileMime.setText(context.getString(R.string.mime, mediaFile.getMimeType()));
55 | holder.fileSize.setText(context.getString(R.string.size, mediaFile.getSize()));
56 | holder.fileBucketName.setText(context.getString(R.string.bucketname, mediaFile.getBucketName()));
57 | if (mediaFile.getMediaType() == MediaFile.TYPE_IMAGE
58 | || mediaFile.getMediaType() == MediaFile.TYPE_VIDEO) {
59 | Glide.with(context)
60 | .load(mediaFile.getUri())
61 | .into(holder.fileThumbnail);
62 | } else if (mediaFile.getMediaType() == MediaFile.TYPE_AUDIO) {
63 | Glide.with(context)
64 | .load(mediaFile.getThumbnail())
65 | .placeholder(R.drawable.ic_audio)
66 | .into(holder.fileThumbnail);
67 | } else {
68 | holder.fileThumbnail.setImageResource(R.drawable.ic_file);
69 | }
70 | }
71 |
72 | @Override
73 | public int getItemCount() {
74 | return mediaFiles.size();
75 | }
76 |
77 | static class ViewHolder extends RecyclerView.ViewHolder {
78 | private ImageView fileThumbnail;
79 | private TextView filePath, fileSize, fileMime, fileBucketName;
80 |
81 | ViewHolder(View view) {
82 | super(view);
83 | fileThumbnail = view.findViewById(R.id.file_thumbnail);
84 | filePath = view.findViewById(R.id.file_path);
85 | fileSize = view.findViewById(R.id.file_size);
86 | fileMime = view.findViewById(R.id.file_mime);
87 | fileBucketName = view.findViewById(R.id.file_bucketname);
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/DirLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.content.ContentUris;
20 | import android.database.Cursor;
21 | import android.net.Uri;
22 | import android.os.Build;
23 | import android.provider.MediaStore;
24 |
25 | import com.jaiselrahman.filepicker.config.Configurations;
26 | import com.jaiselrahman.filepicker.utils.FileUtils;
27 |
28 | import java.util.ArrayList;
29 | import java.util.HashMap;
30 | import java.util.List;
31 |
32 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE;
33 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO;
34 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
35 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
36 |
37 | class DirLoader {
38 | static final String COUNT = "count";
39 |
40 | static final String[] DIR_PROJECTION = new String[]{
41 | MediaStore.Files.FileColumns._ID,
42 | MediaStore.Files.FileColumns.DATA,
43 | MediaStore.Files.FileColumns.BUCKET_ID,
44 | MediaStore.Files.FileColumns.BUCKET_DISPLAY_NAME,
45 | MEDIA_TYPE,
46 | };
47 |
48 | private static final int COLUMN_ID = 0;
49 | private static final int COLUMN_DATA = 1;
50 | private static final int COLUMN_BUCKET_ID = 2;
51 | private static final int COLUMN_BUCKET_DISPLAY_NAME = 3;
52 | private static final int COLUMN_MEDIA_TYPE = 4;
53 | private static final int COLUMN_COUNT = 5;
54 |
55 | static List getDirs(Cursor data, Configurations configs) {
56 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
57 | return getDirsQ(data, configs);
58 | }
59 |
60 | List dirs = new ArrayList<>();
61 | List ignoredPaths = new ArrayList<>();
62 |
63 | if (data.moveToFirst())
64 | do {
65 | String path = data.getString(DirLoader.COLUMN_DATA);
66 | String parent = FileUtils.getParent(path);
67 |
68 | if (!isExcluded(parent, ignoredPaths) && !FileUtils.toIgnoreFolder(path, configs)) {
69 | Dir mediaDir = new Dir();
70 | mediaDir.setId(data.getInt(DirLoader.COLUMN_BUCKET_ID));
71 | mediaDir.setName(data.getString(DirLoader.COLUMN_BUCKET_DISPLAY_NAME));
72 | mediaDir.setCount(data.getInt(DirLoader.COLUMN_COUNT));
73 | mediaDir.setPreview(getPreview(data));
74 | dirs.add(mediaDir);
75 | } else {
76 | ignoredPaths.add(path);
77 | }
78 | } while (data.moveToNext());
79 |
80 | return dirs;
81 | }
82 |
83 | private static List getDirsQ(Cursor data, Configurations configs) {
84 | HashMap dirs = new HashMap<>();
85 | List ignoredPaths = new ArrayList<>();
86 |
87 | if (data.moveToFirst())
88 | do {
89 | String path = data.getString(DirLoader.COLUMN_DATA);
90 | String parent = FileUtils.getParent(path);
91 |
92 | if (!isExcluded(parent, ignoredPaths) && !FileUtils.toIgnoreFolder(path, configs)) {
93 | long dirId = data.getInt(DirLoader.COLUMN_BUCKET_ID);
94 |
95 | Dir mediaDir = dirs.get(dirId);
96 |
97 | if (mediaDir == null) {
98 | mediaDir = new Dir();
99 | mediaDir.setId(dirId);
100 | mediaDir.setName(data.getString(DirLoader.COLUMN_BUCKET_DISPLAY_NAME));
101 | mediaDir.setPreview(getPreview(data));
102 | mediaDir.setCount(1);
103 |
104 | dirs.put(dirId, mediaDir);
105 | } else {
106 | mediaDir.setCount(mediaDir.getCount() + 1);
107 | }
108 | } else {
109 | ignoredPaths.add(path);
110 | }
111 | } while (data.moveToNext());
112 |
113 | return new ArrayList<>(dirs.values());
114 | }
115 |
116 | private static Uri getPreview(Cursor cursor) {
117 | long id = cursor.getLong(DirLoader.COLUMN_ID);
118 | int mediaType = cursor.getInt(DirLoader.COLUMN_MEDIA_TYPE);
119 |
120 | if (id <= 0) return null;
121 |
122 | Uri contentUri;
123 |
124 | if (mediaType == MEDIA_TYPE_IMAGE) {
125 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
126 | } else if (mediaType == MEDIA_TYPE_AUDIO) {
127 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
128 | } else if (mediaType == MEDIA_TYPE_VIDEO) {
129 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
130 | } else {
131 | return null;
132 | }
133 |
134 | return ContentUris.withAppendedId(contentUri, id);
135 | }
136 |
137 | @SuppressWarnings("BooleanMethodIsAlwaysInverted")
138 | private static boolean isExcluded(String path, List ignoredPaths) {
139 | for (String p : ignoredPaths) {
140 | if (path.startsWith(p)) return true;
141 | }
142 | return false;
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/MediaFile.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.net.Uri;
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 |
23 | import androidx.annotation.IntDef;
24 |
25 | public class MediaFile implements Parcelable {
26 | public static final int TYPE_FILE = 0;
27 | public static final int TYPE_IMAGE = 1;
28 | public static final int TYPE_AUDIO = 2;
29 | public static final int TYPE_VIDEO = 3;
30 | public static final int TYPE_MAX = TYPE_VIDEO;
31 |
32 | public static final Creator CREATOR = new Creator() {
33 | @Override
34 | public MediaFile createFromParcel(Parcel in) {
35 | return new MediaFile(in);
36 | }
37 |
38 | @Override
39 | public MediaFile[] newArray(int size) {
40 | return new MediaFile[size];
41 | }
42 | };
43 | private long id, size, duration, date;
44 | private long height, width;
45 | private String name;
46 | private Uri uri;
47 | private Uri thumbnail;
48 | private String path;
49 | private String mimeType;
50 | private String bucketId;
51 | private String bucketName;
52 | private @Type
53 | int mediaType;
54 |
55 | public MediaFile() {
56 | }
57 |
58 | protected MediaFile(Parcel in) {
59 | id = in.readLong();
60 | size = in.readLong();
61 | duration = in.readLong();
62 | date = in.readLong();
63 | height = in.readLong();
64 | width = in.readLong();
65 | name = in.readString();
66 | uri = in.readParcelable(Uri.class.getClassLoader());
67 | thumbnail = in.readParcelable(Uri.class.getClassLoader());
68 | path = in.readString();
69 | mimeType = in.readString();
70 | bucketId = in.readString();
71 | bucketName = in.readString();
72 | mediaType = in.readInt();
73 | }
74 |
75 | @Override
76 | public void writeToParcel(Parcel dest, int flags) {
77 | dest.writeLong(id);
78 | dest.writeLong(size);
79 | dest.writeLong(duration);
80 | dest.writeLong(date);
81 | dest.writeLong(height);
82 | dest.writeLong(width);
83 | dest.writeString(name);
84 | dest.writeParcelable(uri, flags);
85 | dest.writeParcelable(thumbnail, flags);
86 | dest.writeString(path);
87 | dest.writeString(mimeType);
88 | dest.writeString(bucketId);
89 | dest.writeString(bucketName);
90 | dest.writeInt(mediaType);
91 | }
92 |
93 | @Override
94 | public int describeContents() {
95 | return 0;
96 | }
97 |
98 | public Uri getThumbnail() {
99 | return thumbnail;
100 | }
101 |
102 | public Uri getUri() {
103 | return uri;
104 | }
105 |
106 | public void setUri(Uri uri) {
107 | this.uri = uri;
108 | }
109 |
110 | public void setThumbnail(Uri thumbnail) {
111 | this.thumbnail = thumbnail;
112 | }
113 |
114 | public long getHeight() {
115 | return height;
116 | }
117 |
118 | public void setHeight(long height) {
119 | this.height = height;
120 | }
121 |
122 | public long getWidth() {
123 | return width;
124 | }
125 |
126 | public void setWidth(long width) {
127 | this.width = width;
128 | }
129 |
130 | public long getId() {
131 | return id;
132 | }
133 |
134 | public void setId(long id) {
135 | this.id = id;
136 | }
137 |
138 | public long getSize() {
139 | return size;
140 | }
141 |
142 | public void setSize(long size) {
143 | this.size = size;
144 | }
145 |
146 | public long getDuration() {
147 | return duration;
148 | }
149 |
150 | public void setDuration(long duration) {
151 | this.duration = duration;
152 | }
153 |
154 | public String getName() {
155 | return name;
156 | }
157 |
158 | public void setName(String name) {
159 | this.name = name;
160 | }
161 |
162 | @Deprecated
163 | public String getPath() {
164 | return path;
165 | }
166 |
167 | public void setPath(String path) {
168 | this.path = path;
169 | }
170 |
171 | public long getDate() {
172 | return date;
173 | }
174 |
175 | public void setDate(long date) {
176 | this.date = date;
177 | }
178 |
179 | public String getMimeType() {
180 | return mimeType;
181 | }
182 |
183 | public void setMimeType(String mimeType) {
184 | this.mimeType = mimeType;
185 | }
186 |
187 | public String getBucketId() {
188 | return bucketId;
189 | }
190 |
191 | public void setBucketId(String bucketId) {
192 | this.bucketId = bucketId;
193 | }
194 |
195 | public String getBucketName() {
196 | return bucketName;
197 | }
198 |
199 | public void setBucketName(String bucketName) {
200 | this.bucketName = bucketName;
201 | }
202 |
203 | public @Type
204 | int getMediaType() {
205 | return mediaType;
206 | }
207 |
208 | public void setMediaType(@Type int mediaType) {
209 | this.mediaType = mediaType;
210 | }
211 |
212 | @Override
213 | public boolean equals(Object obj) {
214 | return this == obj
215 | || obj instanceof MediaFile && this.uri.equals(((MediaFile) obj).uri);
216 | }
217 |
218 | @Override
219 | public int hashCode() {
220 | return path.hashCode();
221 | }
222 |
223 | @IntDef({TYPE_FILE, TYPE_IMAGE, TYPE_AUDIO, TYPE_VIDEO})
224 | public @interface Type {
225 | }
226 | }
227 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # FilePicker Library for Android
2 |
3 | [](https://opensource.org/licenses/Apache-2.0)
4 | [](https://android-arsenal.com/api?level=14)
5 | [](https://jitpack.io/#jaiselrahman/FilePicker)
6 | [](https://jitpack.io/#jaiselrahman/FilePicker)
7 | [](https://jitpack.io/#jaiselrahman/FilePicker)
8 | [](https://android-arsenal.com/details/1/7002)
9 |
10 | A FilePicker library for Android for selecting multiple types of files and also to capture Images and Videos.
11 |
12 | [Sample Apk](https://github.com/jaiselrahman/FilePicker/releases/download/1.3.0/app-release.apk)
13 |
14 | ## Note
15 |
16 | * For Android 10 please upgrade to version above [1.3.0](https://github.com/jaiselrahman/FilePicker/releases/tag/1.3.0) which contains some [behavior changes](https://github.com/jaiselrahman/FilePicker/releases/tag/1.3.0).
17 | * Uses [MediaStore](https://developer.android.com/reference/android/provider/MediaStore) Database for loading files info.
18 | * Uses [Glide](https://github.com/bumptech/glide) for loading images.
19 |
20 | ## [Screenshots](pics/)
21 |
22 | 
23 |
24 | ## Usage
25 |
26 | Step 1: Add it in your root build.gradle at the end of repositories
27 |
28 | ```gradle
29 | allprojects {
30 | repositories {
31 | ...
32 | maven { url 'https://jitpack.io' }
33 | }
34 | }
35 | ```
36 |
37 | Step 2: Add the dependency
38 |
39 | ```gradle
40 | dependencies {
41 | ...
42 | implementation 'com.github.jaiselrahman:FilePicker:1.3.2'
43 | }
44 | ```
45 |
46 | Step 3: Start FilePickerActivity using ```startActivityForResult(...)```.
47 |
48 | ```java
49 | Intent intent = new Intent(this, FilePickerActivity.class);
50 | startActivityForResult(intent, FILE_REQUEST_CODE);
51 | ```
52 |
53 | Step 4: Receive results in ```onActivityResult(...)```.
54 |
55 | ```java
56 | case FILE_REQUEST_CODE:
57 | ArrayList files = data.getParcelableArrayListExtra(FilePickerActivity.MEDIA_FILES);
58 | //Do something with files
59 | break;
60 | ```
61 |
62 | ## Configuration
63 |
64 | The FilePickerActivity can be configured by using ```Configurations.Builder``` methods
65 |
66 | ### Example
67 |
68 | ```java
69 | intent.putExtra(FilePickerActivity.CONFIGS, new Configurations.Builder()
70 | .setCheckPermission(true)
71 | .setShowImages(true)
72 | .enableImageCapture(true)
73 | .setMaxSelection(10)
74 | .setSkipZeroSizeFiles(true)
75 | .build());
76 | ```
77 |
78 | ### Builder Methods
79 |
80 | |Methods|Default value|Uses|
81 | |-------|-------|---|
82 | |setShowImages(boolean)|true|Whether to load Images files|
83 | |setShowVideos(boolean)|true|Whether to load Videos files|
84 | |setShowAudios(boolean)|false|Whether to load Audio files|
85 | |setShowFiles(boolean)|false|Whether to load Files for given suffixes|
86 | |enableImageCapture(boolean)|false|Enables camera for capturing of images|
87 | |enableVideoCapture(boolean)|false|Enables camera for capturing of videos|
88 | |setCheckPermission(boolean)|false|Whether to request permissions on runtime for API >= 23 if not granted|
89 | |setSuffixes(String...)|"txt", "pdf", "html", "rtf", "csv", "xml",
"zip", "tar", "gz", "rar", "7z","torrent",
"doc", "docx", "odt", "ott",
"ppt", "pptx", "pps",
"xls", "xlsx", "ods", "ots"|Suffixes for file to be loaded, overrides default value|
90 | |setMaxSelection(int)|-1|Maximum no of items to be selected, -1 for no limits|
91 | |setSingleChoiceMode(boolean)|false|Can select only one file, overrides `setMaxSelection(int)`
use `setSelectedMediaFile(MediaFile)` to set default selection|
92 | |setSelectedMediaFile(MediaFile)|null|Default file selection in singleChoiceMode|
93 | |setSelectedMediaFiles(ArrayList\)|null|Default files to be marked as selected|
94 | |setSingleClickSelection(boolean)|true|Start selection mode on single click else on long click|
95 | |setSkipZeroSizeFiles(boolean)|true|Whether to load zero byte sized files|
96 | |setLandscapeSpanCount(int)|5|Grid items in landscape mode|
97 | |setPortraitSpanCount(int)|3|Grid items in portrait mode|
98 | |setImageSize(int)|Screen width/portraitSpanCount |Size of height, width of image to be loaded in Px|
99 | |setRootPath(String)|External storage|Set custom directory path to load files from|
100 | |setIgnorePaths(String... ignorePaths)|null|Regex patterns of paths to ignore|
101 | |setIgnoreNoMedia(boolean)|true|Whether to ignore `.nomedia` file|
102 | |setIgnoreHiddenFile(boolean)|true|Whether to ignore hidden file|
103 |
104 | ## MediaFile methods
105 |
106 | |Method|Description|
107 | |------|-----------|
108 | |long getId()|Id of the file in MediaStore database|
109 | |String getName()|Name of file without suffix|
110 | |String getPath()|Absolute path of the file|
111 | |long getSize()|Size of the file|
112 | |long getDate()|Date when file is added to MediaStore database|
113 | |String getMimeType()|Mime type of the file|
114 | |int getMediaType()|One of TYPE_FILE, TYPE_IMAGE, TYPE_AUDIO, TYPE_VIDEO|
115 | |long getDuration()|Duration of Audio, Video files in ms, else 0|
116 | |Uri getThumbnail()|Album Art of Audio files|
117 | |long getHeight()|Height of Image, Video files in Px for API>=16, else 0|
118 | |long getWidth()|Width of Image, Video files in Px for API>=16, else 0|
119 | |String getBucketId()|Id of Parent Directory in MediaStore database|
120 | |String getBucketName()|Name of Parent Directory|
121 |
122 | ## Contributions
123 |
124 | Feel free to contribute to this project. Before creating issues or pull request please take a look at following templates.
125 |
126 | * [Bug report template](.github/ISSUE_TEMPLATE/bug_report.md)
127 | * [Feature request template](.github/ISSUE_TEMPLATE/feature_request.md)
128 | * [Pull Request template](.github/PULL_REQUEST_TEMPLATE.md)
129 |
130 | ## Credits
131 |
132 | * Inspired by [MultiType-FilePicker](https://github.com/fishwjy/MultiType-FilePicker)
133 |
134 | ## License
135 |
136 | Copyright (c) 2018, Jaisel Rahman
137 |
138 | Licensed under the Apache License, Version 2.0 (the "License");
139 | you may not use this file except in compliance with the License.
140 | You may obtain a copy of the License at
141 |
142 | http://www.apache.org/licenses/LICENSE-2.0
143 |
144 | Unless required by applicable law or agreed to in writing, software
145 | distributed under the License is distributed on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
147 | See the License for the specific language governing permissions and
148 | limitations under the License.
149 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/MediaFileLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.content.ContentResolver;
20 | import android.content.ContentUris;
21 | import android.database.Cursor;
22 | import android.net.Uri;
23 | import android.os.Build;
24 | import android.provider.MediaStore;
25 | import android.text.TextUtils;
26 |
27 | import androidx.annotation.NonNull;
28 | import androidx.annotation.Nullable;
29 |
30 | import com.jaiselrahman.filepicker.config.Configurations;
31 |
32 | import java.util.ArrayList;
33 | import java.util.Arrays;
34 | import java.util.List;
35 |
36 | import static android.provider.BaseColumns._ID;
37 | import static android.provider.MediaStore.Audio.AlbumColumns.ALBUM_ID;
38 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE;
39 | import static android.provider.MediaStore.Files.FileColumns.MIME_TYPE;
40 | import static android.provider.MediaStore.MediaColumns.BUCKET_DISPLAY_NAME;
41 | import static android.provider.MediaStore.MediaColumns.BUCKET_ID;
42 | import static android.provider.MediaStore.MediaColumns.DATA;
43 | import static android.provider.MediaStore.MediaColumns.DATE_ADDED;
44 | import static android.provider.MediaStore.MediaColumns.DISPLAY_NAME;
45 | import static android.provider.MediaStore.MediaColumns.DURATION;
46 | import static android.provider.MediaStore.MediaColumns.HEIGHT;
47 | import static android.provider.MediaStore.MediaColumns.SIZE;
48 | import static android.provider.MediaStore.MediaColumns.WIDTH;
49 |
50 | public class MediaFileLoader {
51 | static final List FILE_PROJECTION = Arrays.asList(
52 | MediaStore.Files.FileColumns._ID,
53 | MediaStore.Files.FileColumns.DISPLAY_NAME,
54 | MediaStore.Files.FileColumns.DATA,
55 | MediaStore.Files.FileColumns.SIZE,
56 | MediaStore.Files.FileColumns.DATE_ADDED,
57 | MediaStore.Files.FileColumns.MIME_TYPE,
58 | MediaStore.Images.Media.BUCKET_ID,
59 | MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
60 | MediaStore.Files.FileColumns.HEIGHT,
61 | MediaStore.Files.FileColumns.WIDTH,
62 | MediaStore.Video.Media.DURATION
63 | );
64 |
65 | @Nullable
66 | public static MediaFile asMediaFile(ContentResolver contentResolver, Uri uri, Configurations configs) {
67 | Cursor data = contentResolver.query(uri, FILE_PROJECTION.toArray(new String[0]), null, null, null);
68 | if (data != null && data.moveToFirst()) {
69 | return asMediaFile(data, configs, uri);
70 | }
71 | return null;
72 | }
73 |
74 | static Uri getContentUri(Configurations configs) {
75 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
76 | (configs.isShowAudios() && !(configs.isShowFiles() || configs.isShowImages() || configs.isShowVideos()))) {
77 | return MediaStore.Audio.Media.getContentUri("external");
78 | } else {
79 | return MediaStore.Files.getContentUri("external");
80 | }
81 | }
82 |
83 | static List asMediaFiles(Cursor data, Configurations configs) {
84 | ArrayList mediaFiles = new ArrayList<>(data.getCount());
85 | if (data.moveToFirst())
86 | do {
87 | MediaFile mediaFile = asMediaFile(data, configs, null);
88 | if (mediaFile != null) {
89 | mediaFiles.add(mediaFile);
90 | }
91 | } while (data.moveToNext());
92 | return mediaFiles;
93 | }
94 |
95 | private static MediaFile asMediaFile(@NonNull Cursor data, Configurations configs, @Nullable Uri uri) {
96 | MediaFile mediaFile = new MediaFile();
97 | mediaFile.setPath(data.getString(data.getColumnIndex(DATA)));
98 |
99 | long size = data.getLong(data.getColumnIndex(SIZE));
100 | //noinspection deprecation
101 | if (size == 0 && mediaFile.getPath() != null) {
102 | //Check if File size is really zero
103 | size = new java.io.File(data.getString(data.getColumnIndex(DATA))).length();
104 | if (size <= 0 && configs.isSkipZeroSizeFiles())
105 | return null;
106 | }
107 | mediaFile.setSize(size);
108 |
109 | mediaFile.setId(data.getLong(data.getColumnIndex(_ID)));
110 | mediaFile.setName(data.getString(data.getColumnIndex(DISPLAY_NAME)));
111 | mediaFile.setPath(data.getString(data.getColumnIndex(DATA)));
112 | mediaFile.setDate(data.getLong(data.getColumnIndex(DATE_ADDED)));
113 | mediaFile.setMimeType(data.getString(data.getColumnIndex(MIME_TYPE)));
114 | mediaFile.setBucketId(data.getString(data.getColumnIndex(BUCKET_ID)));
115 | mediaFile.setBucketName(data.getString(data.getColumnIndex(BUCKET_DISPLAY_NAME)));
116 | mediaFile.setUri(uri != null ? uri : ContentUris.withAppendedId(getContentUri(configs), mediaFile.getId()));
117 | mediaFile.setDuration(data.getLong(data.getColumnIndex(DURATION)));
118 |
119 | if (TextUtils.isEmpty(mediaFile.getName())) {
120 | //noinspection deprecation
121 | String path = mediaFile.getPath() != null ? mediaFile.getPath() : "";
122 | mediaFile.setName(path.substring(path.lastIndexOf('/') + 1));
123 | }
124 |
125 | int mediaTypeIndex = data.getColumnIndex(MEDIA_TYPE);
126 | if (mediaTypeIndex >= 0) {
127 | mediaFile.setMediaType(data.getInt(mediaTypeIndex));
128 | }
129 |
130 | if ((mediaFile.getMediaType() == MediaFile.TYPE_FILE
131 | || mediaFile.getMediaType() > MediaFile.TYPE_MAX)
132 | && mediaFile.getMimeType() != null) {
133 | //Double check correct MediaType
134 | mediaFile.setMediaType(getMediaType(mediaFile.getMimeType()));
135 | }
136 |
137 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
138 | mediaFile.setHeight(data.getLong(data.getColumnIndex(HEIGHT)));
139 | mediaFile.setWidth(data.getLong(data.getColumnIndex(WIDTH)));
140 | }
141 |
142 | int albumIdIndex = data.getColumnIndex(ALBUM_ID);
143 | if (albumIdIndex >= 0) {
144 | int albumId = data.getInt(albumIdIndex);
145 | if (albumId >= 0) {
146 | mediaFile.setThumbnail(ContentUris
147 | .withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId));
148 | }
149 | }
150 | return mediaFile;
151 | }
152 |
153 | private static @MediaFile.Type
154 | int getMediaType(String mime) {
155 | if (mime.startsWith("image/")) {
156 | return MediaFile.TYPE_IMAGE;
157 | } else if (mime.startsWith("video/")) {
158 | return MediaFile.TYPE_VIDEO;
159 | } else if (mime.startsWith("audio/")) {
160 | return MediaFile.TYPE_AUDIO;
161 | } else {
162 | return MediaFile.TYPE_FILE;
163 | }
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/DirDataSource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.content.ContentResolver;
20 | import android.database.Cursor;
21 | import android.net.Uri;
22 | import android.os.Build;
23 | import android.provider.MediaStore;
24 |
25 | import androidx.annotation.NonNull;
26 | import androidx.core.content.ContentResolverCompat;
27 | import androidx.paging.DataSource;
28 | import androidx.paging.PositionalDataSource;
29 |
30 | import com.jaiselrahman.filepicker.config.Configurations;
31 |
32 | import java.io.File;
33 | import java.util.ArrayList;
34 | import java.util.Collections;
35 | import java.util.List;
36 |
37 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE;
38 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO;
39 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
40 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
41 | import static android.provider.MediaStore.MediaColumns.BUCKET_ID;
42 | import static android.provider.MediaStore.MediaColumns.DATA;
43 | import static android.provider.MediaStore.MediaColumns.DATE_ADDED;
44 | import static android.provider.MediaStore.MediaColumns.DATE_MODIFIED;
45 | import static android.provider.MediaStore.MediaColumns.DATE_TAKEN;
46 | import static android.provider.MediaStore.MediaColumns.SIZE;
47 | import static com.jaiselrahman.filepicker.model.MediaFileDataSource.appendDefaultFileSelection;
48 | import static com.jaiselrahman.filepicker.model.MediaFileDataSource.appendFileSelection;
49 |
50 | public class DirDataSource extends PositionalDataSource {
51 | private Configurations configs;
52 | private ContentResolver contentResolver;
53 |
54 | private String[] projection;
55 | private String sortOrder;
56 | private String selection;
57 | private String[] selectionArgs;
58 | private Uri uri;
59 |
60 | private DirDataSource(ContentResolver contentResolver, Uri uri, @NonNull Configurations configs) {
61 | this.contentResolver = contentResolver;
62 | this.configs = configs;
63 | this.uri = uri;
64 |
65 | ArrayList selectionArgs = new ArrayList<>();
66 | StringBuilder selectionBuilder = new StringBuilder(200);
67 |
68 | String rootPath = configs.getRootPath();
69 | if (rootPath != null) {
70 | selectionBuilder.append(DATA).append(" LIKE ? and ");
71 | if (!rootPath.endsWith(File.separator)) rootPath += File.separator;
72 | selectionArgs.add(rootPath + "%");
73 | }
74 |
75 | selectionBuilder.append("(");
76 |
77 | if (configs.isShowImages()) {
78 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
79 | selectionBuilder.append(" or ");
80 | selectionBuilder.append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_IMAGE);
81 | }
82 |
83 | if (configs.isShowVideos()) {
84 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
85 | selectionBuilder.append(" or ");
86 | selectionBuilder.append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_VIDEO);
87 | }
88 |
89 | if (configs.isShowAudios()) {
90 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
91 | selectionBuilder.append(" or ");
92 | selectionBuilder.append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_AUDIO);
93 | }
94 |
95 | if (configs.isShowFiles()) {
96 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
97 | selectionBuilder.append(" or ");
98 |
99 | String[] suffixes = configs.getSuffixes();
100 | if (suffixes != null && suffixes.length > 0) {
101 | appendFileSelection(selectionBuilder, selectionArgs, suffixes);
102 | } else {
103 | appendDefaultFileSelection(selectionBuilder);
104 | }
105 | }
106 |
107 | selectionBuilder.append(") and ");
108 |
109 | if (configs.isSkipZeroSizeFiles()) {
110 | selectionBuilder.append(SIZE).append(" > 0 ").append(" and ");
111 | }
112 |
113 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
114 | selectionBuilder.append(BUCKET_ID).append(" IS NOT NULL) GROUP BY (").append(BUCKET_ID);
115 | } else {
116 | selectionBuilder.append(BUCKET_ID).append(" IS NOT NULL");
117 | }
118 |
119 | this.projection = getDirProjection();
120 | this.sortOrder = DATE_ADDED + " DESC";
121 | this.selection = selectionBuilder.toString();
122 | this.selectionArgs = selectionArgs.toArray(new String[0]);
123 | }
124 |
125 | @Override
126 | public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback callback) {
127 | callback.onResult(getDirs(params.requestedStartPosition, params.requestedLoadSize), 0);
128 | }
129 |
130 | @Override
131 | public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback callback) {
132 | callback.onResult(getDirs(params.startPosition, params.loadSize));
133 | }
134 |
135 | private List getDirs(int offset, int limit) {
136 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
137 | return getDirsQ(offset);
138 | }
139 |
140 | Cursor data = ContentResolverCompat.query(contentResolver, uri, projection,
141 | selection, selectionArgs,
142 | sortOrder + " LIMIT " + limit + " OFFSET " + offset, null);
143 |
144 | return DirLoader.getDirs(data, configs);
145 | }
146 |
147 | private List getDirsQ(int offset) {
148 | if (offset != 0) return Collections.emptyList();
149 |
150 | Cursor data = ContentResolverCompat.query(contentResolver, uri, projection,
151 | selection, selectionArgs,
152 | sortOrder, null);
153 |
154 | return DirLoader.getDirs(data, configs);
155 | }
156 |
157 | private static String[] getDirProjection() {
158 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
159 | return DirLoader.DIR_PROJECTION;
160 | }
161 |
162 | List projection = new ArrayList<>();
163 | Collections.addAll(projection, DirLoader.DIR_PROJECTION);
164 | projection.add("COUNT(*) as " + DirLoader.COUNT);
165 |
166 | return projection.toArray(new String[0]);
167 | }
168 |
169 | public static class Factory extends DataSource.Factory {
170 | private ContentResolver contentResolver;
171 | private Configurations configs;
172 |
173 | private Uri uri;
174 |
175 | Factory(ContentResolver contentResolver, Configurations configs) {
176 | this.contentResolver = contentResolver;
177 | this.configs = configs;
178 |
179 | uri = MediaStore.Files.getContentUri("external");
180 | }
181 |
182 | public Uri getUri() {
183 | return uri;
184 | }
185 |
186 | @NonNull
187 | @Override
188 | public DataSource create() {
189 | return new DirDataSource(contentResolver, uri, configs);
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/app/src/main/java/com/jaiselrahman/filepickersample/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepickersample;
18 |
19 | import android.content.Intent;
20 | import android.os.Bundle;
21 | import android.view.Menu;
22 | import android.view.MenuItem;
23 | import android.view.View;
24 | import android.widget.Toast;
25 |
26 | import androidx.activity.result.ActivityResultCallback;
27 | import androidx.activity.result.ActivityResultLauncher;
28 | import androidx.appcompat.app.AppCompatActivity;
29 | import androidx.recyclerview.widget.RecyclerView;
30 |
31 | import com.jaiselrahman.filepicker.activity.DirSelectActivity;
32 | import com.jaiselrahman.filepicker.activity.FilePickerActivity;
33 | import com.jaiselrahman.filepicker.activity.PickFile;
34 | import com.jaiselrahman.filepicker.config.Configurations;
35 | import com.jaiselrahman.filepicker.model.MediaFile;
36 | import com.jaiselrahman.filepicker.utils.FilePickerProvider;
37 |
38 | import java.io.File;
39 | import java.io.IOException;
40 | import java.util.ArrayList;
41 | import java.util.List;
42 |
43 | public class MainActivity extends AppCompatActivity {
44 | private final static int FILE_REQUEST_CODE = 1;
45 | private FileListAdapter fileListAdapter;
46 | private ArrayList mediaFiles = new ArrayList<>();
47 |
48 | @Override
49 | protected void onCreate(Bundle savedInstanceState) {
50 | super.onCreate(savedInstanceState);
51 | setContentView(R.layout.activity_main);
52 | RecyclerView recyclerView = findViewById(R.id.file_list);
53 | fileListAdapter = new FileListAdapter(mediaFiles);
54 | recyclerView.setAdapter(fileListAdapter);
55 |
56 | final ActivityResultLauncher pickImage = registerForActivityResult(new PickFile().throughDir(true), new ActivityResultCallback>() {
57 | @Override
58 | public void onActivityResult(List result) {
59 | if (result != null)
60 | setMediaFiles(result);
61 | else
62 | Toast.makeText(MainActivity.this, "Image not selected", Toast.LENGTH_SHORT).show();
63 | }
64 | });
65 |
66 | findViewById(R.id.launch_imagePicker).setOnClickListener(new View.OnClickListener() {
67 | @Override
68 | public void onClick(View v) {
69 | pickImage.launch(new Configurations.Builder()
70 | .setCheckPermission(true)
71 | .setSelectedMediaFiles(mediaFiles)
72 | .enableImageCapture(true)
73 | .setShowVideos(false)
74 | .setSkipZeroSizeFiles(true)
75 | .setMaxSelection(10)
76 | .build());
77 | }
78 | });
79 |
80 | findViewById(R.id.launch_videoPicker).setOnClickListener(new View.OnClickListener() {
81 | @Override
82 | public void onClick(View v) {
83 | Intent intent = new Intent(MainActivity.this, FilePickerActivity.class);
84 | intent.putExtra(FilePickerActivity.CONFIGS, new Configurations.Builder()
85 | .setCheckPermission(true)
86 | .setSelectedMediaFiles(mediaFiles)
87 | .enableVideoCapture(true)
88 | .setShowImages(false)
89 | .setMaxSelection(10)
90 | .setIgnorePaths(".*WhatsApp.*")
91 | .build());
92 | startActivityForResult(intent, FILE_REQUEST_CODE);
93 | }
94 | });
95 |
96 | findViewById(R.id.launch_audioPicker).setOnClickListener(new View.OnClickListener() {
97 | @Override
98 | public void onClick(View v) {
99 | Intent intent = new Intent(MainActivity.this, FilePickerActivity.class);
100 | MediaFile file = null;
101 | for (int i = 0; i < mediaFiles.size(); i++) {
102 | if (mediaFiles.get(i).getMediaType() == MediaFile.TYPE_AUDIO) {
103 | file = mediaFiles.get(i);
104 | }
105 | }
106 | intent.putExtra(FilePickerActivity.CONFIGS, new Configurations.Builder()
107 | .setCheckPermission(true)
108 | .setShowImages(false)
109 | .setShowVideos(false)
110 | .setShowAudios(true)
111 | .setSingleChoiceMode(true)
112 | .setSelectedMediaFile(file)
113 | .setTitle("Select an audio")
114 | .build());
115 | startActivityForResult(intent, FILE_REQUEST_CODE);
116 | }
117 | });
118 |
119 | findViewById(R.id.launch_filePicker).setOnClickListener(new View.OnClickListener() {
120 | @Override
121 | public void onClick(View v) {
122 | Intent intent = new Intent(MainActivity.this, DirSelectActivity.class);
123 | intent.putExtra(DirSelectActivity.CONFIGS, new Configurations.Builder()
124 | .setCheckPermission(true)
125 | .setSelectedMediaFiles(mediaFiles)
126 | .setShowFiles(true)
127 | .setShowImages(true)
128 | .setShowAudios(true)
129 | .setShowVideos(true)
130 | .setIgnoreNoMedia(false)
131 | .enableVideoCapture(true)
132 | .enableImageCapture(true)
133 | .setIgnoreHiddenFile(false)
134 | .setMaxSelection(10)
135 | .setTitle("Select a file")
136 | .build());
137 | startActivityForResult(intent, FILE_REQUEST_CODE);
138 | }
139 | });
140 | }
141 |
142 | @Override
143 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
144 | super.onActivityResult(requestCode, resultCode, data);
145 | if (requestCode == FILE_REQUEST_CODE
146 | && resultCode == RESULT_OK
147 | && data != null) {
148 | List mediaFiles = data.getParcelableArrayListExtra(FilePickerActivity.MEDIA_FILES);
149 | if(mediaFiles != null) {
150 | setMediaFiles(mediaFiles);
151 | } else {
152 | Toast.makeText(MainActivity.this, "Image not selected", Toast.LENGTH_SHORT).show();
153 | }
154 | }
155 | }
156 |
157 | private void setMediaFiles(List mediaFiles) {
158 | this.mediaFiles.clear();
159 | this.mediaFiles.addAll(mediaFiles);
160 | fileListAdapter.notifyDataSetChanged();
161 | }
162 |
163 | @Override
164 | public boolean onCreateOptionsMenu(Menu menu) {
165 | getMenuInflater().inflate(R.menu.menu_main, menu);
166 | return true;
167 | }
168 |
169 | @Override
170 | public boolean onOptionsItemSelected(MenuItem item) {
171 | if (item.getItemId() == R.id.share_log) {
172 | shareLogFile();
173 | return true;
174 | }
175 | return super.onOptionsItemSelected(item);
176 | }
177 |
178 | public void shareLogFile() {
179 | File logFile = new File(getExternalCacheDir(), "logcat.txt");
180 | try {
181 | if (logFile.exists())
182 | logFile.delete();
183 | logFile.createNewFile();
184 | Runtime.getRuntime().exec("logcat -f " + logFile.getAbsolutePath() + " -t 100 *:W Glide:S " + FilePickerActivity.TAG);
185 | } catch (IOException e) {
186 | e.printStackTrace();
187 | }
188 |
189 | if (logFile.exists()) {
190 | Intent intentShareFile = new Intent(Intent.ACTION_SEND);
191 | intentShareFile.setType("text/plain");
192 | intentShareFile.putExtra(Intent.EXTRA_STREAM,
193 | FilePickerProvider.getUriForFile(this, logFile));
194 | intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "FilePicker Log File");
195 | intentShareFile.putExtra(Intent.EXTRA_TEXT, "FilePicker Log File");
196 | startActivity(Intent.createChooser(intentShareFile, "Share"));
197 | }
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/adapter/DirListAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.adapter;
18 |
19 | import android.app.Activity;
20 | import android.content.ContentValues;
21 | import android.content.Intent;
22 | import android.net.Uri;
23 | import android.provider.MediaStore;
24 | import android.util.Log;
25 | import android.view.LayoutInflater;
26 | import android.view.View;
27 | import android.view.ViewGroup;
28 | import android.widget.ImageView;
29 | import android.widget.TextView;
30 |
31 | import androidx.annotation.NonNull;
32 | import androidx.paging.AsyncPagedListDiffer;
33 | import androidx.paging.PagedList;
34 | import androidx.recyclerview.widget.AsyncDifferConfig;
35 | import androidx.recyclerview.widget.DiffUtil;
36 | import androidx.recyclerview.widget.ListUpdateCallback;
37 | import androidx.recyclerview.widget.RecyclerView;
38 |
39 | import com.bumptech.glide.Glide;
40 | import com.bumptech.glide.RequestManager;
41 | import com.bumptech.glide.request.RequestOptions;
42 | import com.jaiselrahman.filepicker.R;
43 | import com.jaiselrahman.filepicker.model.Dir;
44 | import com.jaiselrahman.filepicker.utils.FilePickerProvider;
45 | import com.jaiselrahman.filepicker.view.SquareImage;
46 |
47 | import java.io.File;
48 | import java.text.SimpleDateFormat;
49 | import java.util.Date;
50 | import java.util.Locale;
51 |
52 | import static android.os.Environment.DIRECTORY_MOVIES;
53 | import static android.os.Environment.DIRECTORY_PICTURES;
54 | import static android.os.Environment.getExternalStoragePublicDirectory;
55 | import static com.jaiselrahman.filepicker.activity.FilePickerActivity.TAG;
56 |
57 | public class DirListAdapter extends RecyclerView.Adapter implements ListUpdateCallback {
58 | public static final int CAPTURE_IMAGE_VIDEO = 1;
59 | private Activity activity;
60 | private RequestManager glideRequest;
61 | private OnClickListener onClickListener;
62 | private OnCameraClickListener onCameraClickListener;
63 | private boolean showCamera;
64 | private boolean showVideoCamera;
65 | private File lastCapturedFile;
66 | private Uri lastCapturedUri;
67 | private int itemStartPosition;
68 | private SimpleDateFormat TimeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
69 |
70 | private AsyncPagedListDiffer differ = new AsyncPagedListDiffer<>(this, new AsyncDifferConfig.Builder<>(DIR_ITEM_CALLBACK).build());
71 |
72 | public DirListAdapter(Activity activity, int imageSize, boolean showCamera, boolean showVideoCamera) {
73 | this.activity = activity;
74 | this.showCamera = showCamera;
75 | this.showVideoCamera = showVideoCamera;
76 | glideRequest = Glide.with(this.activity)
77 | .applyDefaultRequestOptions(RequestOptions
78 | .sizeMultiplierOf(0.70f)
79 | .optionalCenterCrop()
80 | .placeholder(R.drawable.ic_dir)
81 | .override(imageSize));
82 |
83 | if (showCamera && showVideoCamera)
84 | itemStartPosition = 2;
85 | else if (showCamera || showVideoCamera)
86 | itemStartPosition = 1;
87 | }
88 |
89 | public File getLastCapturedFile() {
90 | return lastCapturedFile;
91 | }
92 |
93 | public void setLastCapturedFile(File file) {
94 | lastCapturedFile = file;
95 | }
96 |
97 | public Uri getLastCapturedUri() {
98 | return lastCapturedUri;
99 | }
100 |
101 | public void setLastCapturedUri(Uri uri) {
102 | lastCapturedUri = uri;
103 | }
104 |
105 | @NonNull
106 | @Override
107 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
108 | View v = LayoutInflater.from(activity)
109 | .inflate(R.layout.filepicker_dir_item, parent, false);
110 | return new ViewHolder(v, onClickListener);
111 | }
112 |
113 | @Override
114 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
115 | if (showCamera) {
116 | if (position == 0) {
117 | handleCamera(holder.openCamera, false);
118 | return;
119 | }
120 | if (showVideoCamera) {
121 | if (position == 1) {
122 | handleCamera(holder.openVideoCamera, true);
123 | return;
124 | }
125 | holder.openVideoCamera.setVisibility(View.GONE);
126 | position--;
127 | }
128 | holder.openCamera.setVisibility(View.GONE);
129 | position--;
130 | } else if (showVideoCamera) {
131 | if (position == 0) {
132 | handleCamera(holder.openVideoCamera, true);
133 | return;
134 | }
135 | holder.openVideoCamera.setVisibility(View.GONE);
136 | position--;
137 | }
138 |
139 | holder.dir = getItem(position);
140 |
141 | holder.dirName.setText(holder.dir.getName());
142 | holder.dirCount.setText(String.valueOf(holder.dir.getCount()));
143 |
144 | Uri preview = holder.dir.getPreview();
145 | if (preview != null)
146 | glideRequest.load(holder.dir.getPreview())
147 | .into(holder.dirPreview);
148 | else
149 | holder.dirPreview.setImageResource(R.drawable.ic_dir);
150 | }
151 |
152 | private void handleCamera(final ImageView openCamera, final boolean forVideo) {
153 | openCamera.setVisibility(View.VISIBLE);
154 | openCamera.setOnClickListener(new View.OnClickListener() {
155 | @Override
156 | public void onClick(View v) {
157 | if (onCameraClickListener != null && !onCameraClickListener.onCameraClick(forVideo))
158 | return;
159 | openCamera(forVideo);
160 | }
161 | });
162 | }
163 |
164 | public void openCamera(boolean forVideo) {
165 | Intent intent;
166 | String fileName;
167 | File dir;
168 | Uri externalContentUri;
169 | if (forVideo) {
170 | intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
171 | fileName = "/VID_" + getTimeStamp() + ".mp4";
172 | dir = getExternalStoragePublicDirectory(DIRECTORY_MOVIES);
173 | externalContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
174 | } else {
175 | intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
176 | dir = getExternalStoragePublicDirectory(DIRECTORY_PICTURES);
177 | fileName = "/IMG_" + getTimeStamp() + ".jpeg";
178 | externalContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
179 | }
180 | if (!dir.exists() && !dir.mkdir()) {
181 | Log.d(TAG, "onClick: " +
182 | (forVideo ? "MOVIES" : "PICTURES") + " Directory not exists");
183 | return;
184 | }
185 | lastCapturedFile = new File(dir.getAbsolutePath() + fileName);
186 |
187 | Uri fileUri = FilePickerProvider.getUriForFile(activity, lastCapturedFile);
188 |
189 | ContentValues values = new ContentValues();
190 | values.put(MediaStore.MediaColumns.DATA, lastCapturedFile.getAbsolutePath());
191 | values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis());
192 | lastCapturedUri = activity.getContentResolver().insert(externalContentUri, values);
193 |
194 | intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
195 | activity.startActivityForResult(intent, CAPTURE_IMAGE_VIDEO);
196 | }
197 |
198 | private String getTimeStamp() {
199 | return TimeStamp.format(new Date());
200 | }
201 |
202 | public void setOnClickListener(OnClickListener onClickListener) {
203 | this.onClickListener = onClickListener;
204 | }
205 |
206 | public void setOnCameraClickListener(OnCameraClickListener onCameraClickListener) {
207 | this.onCameraClickListener = onCameraClickListener;
208 | }
209 |
210 | private Dir getItem(int position) {
211 | return differ.getItem(position);
212 | }
213 |
214 | @Override
215 | public int getItemCount() {
216 | if (showCamera) {
217 | if (showVideoCamera)
218 | return differ.getItemCount() + 2;
219 | return differ.getItemCount() + 1;
220 | } else if (showVideoCamera) {
221 | return differ.getItemCount() + 1;
222 | }
223 | return differ.getItemCount();
224 | }
225 |
226 | @Override
227 | public void onInserted(int position, int count) {
228 | notifyItemRangeInserted(itemStartPosition + position, count);
229 | }
230 |
231 | @Override
232 | public void onRemoved(int position, int count) {
233 | notifyItemRangeRemoved(itemStartPosition + position, count);
234 | }
235 |
236 | @Override
237 | public void onMoved(int fromPosition, int toPosition) {
238 | notifyItemMoved(itemStartPosition + fromPosition, itemStartPosition + toPosition);
239 | }
240 |
241 | @Override
242 | public void onChanged(int position, int count, Object payload) {
243 | notifyItemRangeChanged(itemStartPosition + position, count, payload);
244 | }
245 |
246 | public void submitList(PagedList dirs) {
247 | differ.submitList(dirs);
248 | }
249 |
250 | static class ViewHolder extends RecyclerView.ViewHolder {
251 | private ImageView openCamera, openVideoCamera;
252 | private SquareImage dirPreview;
253 | private TextView dirName;
254 | private TextView dirCount;
255 | private Dir dir;
256 |
257 | ViewHolder(View v, final OnClickListener onClickListener) {
258 | super(v);
259 | openCamera = v.findViewById(R.id.file_open_camera);
260 | openVideoCamera = v.findViewById(R.id.file_open_video_camera);
261 | dirPreview = v.findViewById(R.id.dir_preview);
262 | dirName = v.findViewById(R.id.dir_name);
263 | dirCount = v.findViewById(R.id.dir_count);
264 |
265 | v.setOnClickListener(new View.OnClickListener() {
266 | @Override
267 | public void onClick(View v) {
268 | onClickListener.onClick(dir);
269 | }
270 | });
271 | }
272 | }
273 |
274 | public interface OnCameraClickListener {
275 | boolean onCameraClick(boolean forVideo);
276 | }
277 |
278 | public interface OnClickListener {
279 | void onClick(Dir dir);
280 | }
281 |
282 | private static final DiffUtil.ItemCallback DIR_ITEM_CALLBACK = new DiffUtil.ItemCallback() {
283 | @Override
284 | public boolean areItemsTheSame(@NonNull Dir oldItem, @NonNull Dir newItem) {
285 | return oldItem.getId() == newItem.getId();
286 | }
287 |
288 | @Override
289 | public boolean areContentsTheSame(@NonNull Dir oldItem, @NonNull Dir newItem) {
290 | return (oldItem.getName() != null && oldItem.getName().equals(newItem.getName()))
291 | && oldItem.getCount() == newItem.getCount()
292 | && ((oldItem.getPreview() == null && newItem.getPreview() == null)
293 | || (oldItem.getPreview() !=null && oldItem.getPreview().equals(newItem.getPreview())));
294 | }
295 | };
296 | }
297 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/model/MediaFileDataSource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2020, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.model;
18 |
19 | import android.content.ContentResolver;
20 | import android.database.Cursor;
21 | import android.net.Uri;
22 | import android.os.Build;
23 | import android.provider.MediaStore;
24 |
25 | import androidx.annotation.NonNull;
26 | import androidx.core.content.ContentResolverCompat;
27 | import androidx.paging.DataSource;
28 | import androidx.paging.PositionalDataSource;
29 |
30 | import com.jaiselrahman.filepicker.config.Configurations;
31 | import com.jaiselrahman.filepicker.utils.FileUtils;
32 |
33 | import java.io.File;
34 | import java.util.ArrayList;
35 | import java.util.List;
36 |
37 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE;
38 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO;
39 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
40 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_NONE;
41 | import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
42 | import static android.provider.MediaStore.MediaColumns.BUCKET_ID;
43 | import static android.provider.MediaStore.MediaColumns.DATA;
44 | import static android.provider.MediaStore.MediaColumns.DATE_ADDED;
45 | import static android.provider.MediaStore.MediaColumns.DISPLAY_NAME;
46 | import static android.provider.MediaStore.MediaColumns.SIZE;
47 |
48 | public class MediaFileDataSource extends PositionalDataSource {
49 |
50 | private Configurations configs;
51 | private ContentResolver contentResolver;
52 |
53 | private String[] projection;
54 | private String sortOrder;
55 | private String selection;
56 | private String[] selectionArgs;
57 | private Uri uri;
58 |
59 | private MediaFileDataSource(ContentResolver contentResolver, Uri uri, @NonNull Configurations configs, Long dirId) {
60 | this.contentResolver = contentResolver;
61 | this.configs = configs;
62 | this.uri = uri;
63 |
64 | StringBuilder selectionBuilder = new StringBuilder(100);
65 |
66 | ArrayList selectionArgs = new ArrayList<>();
67 |
68 | String rootPath = configs.getRootPath();
69 | if (rootPath != null) {
70 | selectionBuilder.append(DATA).append(" LIKE ? and ");
71 | if (!rootPath.endsWith(File.separator)) rootPath += File.separator;
72 | selectionArgs.add(rootPath + "%");
73 | }
74 |
75 | if (dirId != null) {
76 | if (selectionBuilder.length() != 0)
77 | selectionBuilder.append(" and ");
78 | selectionBuilder.append(BUCKET_ID).append("=").append(dirId).append(" and ");
79 | }
80 |
81 | if (canUseMediaType(configs)) {
82 |
83 | selectionBuilder.append("(");
84 |
85 | if (configs.isShowImages()) {
86 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
87 | selectionBuilder.append(" or ");
88 | selectionBuilder.append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_IMAGE);
89 | }
90 |
91 | if (configs.isShowVideos()) {
92 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
93 | selectionBuilder.append(" or ");
94 | selectionBuilder.append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_VIDEO);
95 | }
96 |
97 | if (configs.isShowAudios()) {
98 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
99 | selectionBuilder.append(" or ");
100 | selectionBuilder.append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_AUDIO);
101 | }
102 |
103 | if (configs.isShowFiles()) {
104 | if (selectionBuilder.charAt(selectionBuilder.length() - 1) != '(')
105 | selectionBuilder.append(" or ");
106 |
107 | String[] suffixes = configs.getSuffixes();
108 | if (suffixes != null && suffixes.length > 0) {
109 | appendFileSelection(selectionBuilder, selectionArgs, suffixes);
110 | } else {
111 | appendDefaultFileSelection(selectionBuilder);
112 | }
113 | }
114 | selectionBuilder.append(") and ");
115 | }
116 |
117 | if (configs.isSkipZeroSizeFiles()) {
118 | selectionBuilder.append(SIZE).append(" > 0 ");
119 | }
120 |
121 | List projection = new ArrayList<>(MediaFileLoader.FILE_PROJECTION);
122 |
123 | if (canUseMediaType(configs)) {
124 | projection.add(MediaStore.Files.FileColumns.MEDIA_TYPE);
125 | }
126 |
127 | if (canUseAlbumId(configs)) {
128 | projection.add(MediaStore.Audio.AudioColumns.ALBUM_ID);
129 | }
130 |
131 | List folders = getFoldersToIgnore(contentResolver, configs);
132 | if (folders.size() > 0) {
133 | selectionBuilder.append(" and(").append(DATA).append(" NOT LIKE ? ");
134 | selectionArgs.add(folders.get(0) + "%");
135 | int size = folders.size();
136 | for (int i = 1; i < size; i++) {
137 | selectionBuilder.append(" and ").append(DATA).append(" NOT LIKE ? ");
138 | selectionArgs.add(folders.get(i) + "%");
139 | }
140 | selectionBuilder.append(")");
141 | }
142 |
143 | this.projection = projection.toArray(new String[0]);
144 | this.sortOrder = DATE_ADDED + " DESC";
145 | this.selection = selectionBuilder.toString();
146 | this.selectionArgs = selectionArgs.toArray(new String[0]);
147 | }
148 |
149 | @Override
150 | public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback callback) {
151 | callback.onResult(getMediaFiles(params.requestedStartPosition, params.requestedLoadSize), 0);
152 | }
153 |
154 | @Override
155 | public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback callback) {
156 | callback.onResult(getMediaFiles(params.startPosition, params.loadSize));
157 | }
158 |
159 | private List getMediaFiles(int offset, int limit) {
160 | Cursor data = ContentResolverCompat.query(contentResolver, uri, projection,
161 | selection, selectionArgs,
162 | sortOrder + " LIMIT " + limit + " OFFSET " + offset, null);
163 |
164 | return MediaFileLoader.asMediaFiles(data, configs);
165 | }
166 |
167 | private static boolean canUseAlbumId(Configurations configs) {
168 | return Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ||
169 | (configs.isShowAudios() && !(configs.isShowFiles() || configs.isShowImages() || configs.isShowVideos()));
170 | }
171 |
172 | private static boolean canUseMediaType(Configurations configs) {
173 | return Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ||
174 | (!configs.isShowAudios() && (configs.isShowFiles() || configs.isShowImages() || configs.isShowVideos()));
175 | }
176 |
177 | @NonNull
178 | private static List getFoldersToIgnore(ContentResolver contentResolver, Configurations configs) {
179 | Uri uri = MediaStore.Files.getContentUri("external");
180 |
181 | String[] projection = new String[]{DATA};
182 |
183 | String selection;
184 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
185 | selection = BUCKET_ID + " IS NOT NULL) GROUP BY (" + BUCKET_ID;
186 | } else {
187 | selection = BUCKET_ID + " IS NOT NULL";
188 | }
189 |
190 | String sortOrder = DATA + " ASC";
191 |
192 | Cursor cursor = ContentResolverCompat.query(
193 | contentResolver, uri, projection, selection,
194 | null, sortOrder, null
195 | );
196 | if (cursor == null) {
197 | return new ArrayList<>();
198 | }
199 |
200 | int dataColumnIndex = cursor.getColumnIndex(DATA);
201 |
202 | ArrayList folders = new ArrayList<>();
203 | try {
204 | if (cursor.moveToFirst()) {
205 | do {
206 | String path = cursor.getString(dataColumnIndex);
207 | String parent = FileUtils.getParent(path);
208 | if (!isExcluded(parent, folders) && FileUtils.toIgnoreFolder(path, configs)) {
209 | folders.add(parent);
210 | }
211 | } while (cursor.moveToNext());
212 | }
213 | } catch (Exception e) {
214 | e.printStackTrace();
215 | }
216 | cursor.close();
217 |
218 | return folders;
219 | }
220 |
221 | static void appendDefaultFileSelection(StringBuilder selection) {
222 | selection.append("(")
223 | .append("(")
224 | .append(MEDIA_TYPE).append(" = ").append(MEDIA_TYPE_NONE)
225 | .append(" or ")
226 | .append(MEDIA_TYPE).append(" > ").append(MEDIA_TYPE_VIDEO)
227 | .append(")and ")
228 | .append(MediaStore.Files.FileColumns.MIME_TYPE).append(" <> 'resource/folder'")
229 | .append(" and ")
230 | .append(MediaStore.Files.FileColumns.MIME_TYPE).append(" NOT LIKE 'image/%'")
231 | .append(" and ")
232 | .append(MediaStore.Files.FileColumns.MIME_TYPE).append(" NOT LIKE 'video/%'")
233 | .append(" and ")
234 | .append(MediaStore.Files.FileColumns.MIME_TYPE).append(" NOT LIKE 'audio/%'")
235 | .append(")");
236 | }
237 |
238 | static void appendFileSelection(StringBuilder selectionBuilder, List selectionArgs, String[] suffixes) {
239 | selectionBuilder.append("(").append(DISPLAY_NAME).append(" LIKE ?");
240 | selectionArgs.add("%." + suffixes[0].replace(".", ""));
241 |
242 | int size = suffixes.length;
243 | for (int i = 1; i < size; i++) {
244 | selectionBuilder.append(" or ").append(DISPLAY_NAME).append(" LIKE ?");
245 | suffixes[i] = suffixes[i].replace(".", "");
246 | selectionArgs.add("%." + suffixes[i]);
247 | }
248 |
249 | selectionBuilder.append(")");
250 | }
251 |
252 | private static boolean isExcluded(String path, List ignoredPaths) {
253 | for (String p : ignoredPaths) {
254 | if (path.startsWith(p)) return true;
255 | }
256 | return false;
257 | }
258 |
259 | public static class Factory extends DataSource.Factory {
260 | private ContentResolver contentResolver;
261 | private Configurations configs;
262 | private Long dirId;
263 |
264 | private Uri uri;
265 |
266 | Factory(ContentResolver contentResolver, Configurations configs, Long dirId) {
267 | this.contentResolver = contentResolver;
268 | this.configs = configs;
269 | this.dirId = dirId;
270 |
271 | uri = MediaFileLoader.getContentUri(configs);
272 | }
273 |
274 | public Uri getUri() {
275 | return uri;
276 | }
277 |
278 | @NonNull
279 | @Override
280 | public DataSource create() {
281 | return new MediaFileDataSource(contentResolver, uri, configs, dirId);
282 | }
283 | }
284 | }
285 |
--------------------------------------------------------------------------------
/filepicker/src/main/java/com/jaiselrahman/filepicker/adapter/MultiSelectionAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018, Jaisel Rahman .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.jaiselrahman.filepicker.adapter;
18 |
19 | import android.view.View;
20 |
21 | import androidx.annotation.CallSuper;
22 | import androidx.annotation.NonNull;
23 | import androidx.paging.AsyncPagedListDiffer;
24 | import androidx.recyclerview.widget.RecyclerView;
25 |
26 | import com.jaiselrahman.filepicker.model.MediaFile;
27 |
28 | import java.util.ArrayList;
29 | import java.util.List;
30 |
31 | @SuppressWarnings({"unused", "WeakerAccess"})
32 | public abstract class MultiSelectionAdapter extends RecyclerView.Adapter {
33 | private static final String TAG = MultiSelectionAdapter.class.getSimpleName();
34 | private ArrayList selectedItems = new ArrayList<>();
35 |
36 | private OnItemClickListener onItemClickListener;
37 | private OnItemLongClickListener onItemLongClickListener;
38 | private OnSelectionListener customOnSelectionListener;
39 | private boolean isSelectionStarted = false;
40 | private boolean enabledSelection = false;
41 | private boolean isSingleClickSelection = false;
42 | private boolean singleChoiceMode = false;
43 | private int maxSelection = -1;
44 | protected int itemStartPosition = 0;
45 | private AsyncPagedListDiffer differ;
46 |
47 | private OnSelectionListener onSelectionListener = new OnSelectionListener() {
48 | @Override
49 | public void onSelectionBegin() {
50 | isSelectionStarted = true;
51 | if (!singleChoiceMode && customOnSelectionListener != null)
52 | customOnSelectionListener.onSelectionBegin();
53 | }
54 |
55 | @Override
56 | public void onSelected(VH viewHolder, int position) {
57 | if (singleChoiceMode && selectedItems.size() > 0) {
58 | int pos = getCurrentList().indexOf(selectedItems.get(0));
59 | if (pos >= 0) {
60 | removeSelection(pos);
61 | handleItemChanged(pos);
62 | }
63 | }
64 | if (maxSelection > 0 && selectedItems.size() >= maxSelection) {
65 | onMaxReached();
66 | return;
67 | }
68 | setItemSelected(viewHolder.itemView, position, true);
69 | if (customOnSelectionListener != null)
70 | customOnSelectionListener.onSelected(viewHolder, position);
71 | }
72 |
73 | @Override
74 | public void onUnSelected(VH viewHolder, int position) {
75 | setItemSelected(viewHolder.itemView, position, false);
76 | if (customOnSelectionListener != null)
77 | customOnSelectionListener.onUnSelected(viewHolder, position);
78 | }
79 |
80 | @Override
81 | public void onSelectAll() {
82 | isSelectionStarted = true;
83 | selectedItems.clear();
84 | selectedItems.addAll(getCurrentList());
85 | notifyDataSetChanged();
86 | if (customOnSelectionListener != null)
87 | customOnSelectionListener.onSelectAll();
88 | }
89 |
90 | @Override
91 | public void onUnSelectAll() {
92 | for (int i = selectedItems.size() - 1; i >= 0; i--) {
93 | int position = getCurrentList().indexOf(selectedItems.get(i));
94 | if (position < 0) continue;
95 | removeSelection(position);
96 | handleItemChanged(position);
97 | }
98 | isSelectionStarted = false;
99 | if (customOnSelectionListener != null)
100 | customOnSelectionListener.onUnSelectAll();
101 | }
102 |
103 | @Override
104 | public void onSelectionEnd() {
105 | isSelectionStarted = false;
106 | if (!singleChoiceMode && customOnSelectionListener != null)
107 | customOnSelectionListener.onSelectionEnd();
108 | }
109 |
110 | @Override
111 | public void onMaxReached() {
112 | if (!singleChoiceMode && customOnSelectionListener != null)
113 | customOnSelectionListener.onMaxReached();
114 | }
115 | };
116 |
117 | public void setDiffer(AsyncPagedListDiffer differ) {
118 | this.differ = differ;
119 | }
120 |
121 | public void setItemStartPosition(int itemStartPosition) {
122 | this.itemStartPosition = itemStartPosition;
123 | }
124 |
125 | public int getMaxSelection() {
126 | return maxSelection;
127 | }
128 |
129 | public void setMaxSelection(int maxSelection) {
130 | this.maxSelection = maxSelection;
131 | }
132 |
133 | protected MediaFile getItem(int position) {
134 | return differ.getItem(position);
135 | }
136 |
137 | protected List getCurrentList() {
138 | return differ.getCurrentList();
139 | }
140 |
141 | @Override
142 | public int getItemCount() {
143 | return differ.getItemCount();
144 | }
145 |
146 | @CallSuper
147 | @Override
148 | public void onBindViewHolder(@NonNull final VH holder, int position) {
149 | setItemSelected(holder.itemView, position, selectedItems.contains(getItem(position)));
150 | }
151 |
152 | @Override
153 | public void onBindViewHolder(@NonNull VH holder, int position, @NonNull List