- How to get dir file list in Android 11
- 4 Answers 4
- Android: List External Storage Files
- android, how to get directory listing?
- 5 Answers 5
- Not the answer you’re looking for? Browse other questions tagged java android or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to list files in an android directory?
- 12 Answers 12
- Updated working method
- MainActivity.java
- How do I list all file in a directory in android 10 using Android Studio?
- 5 Answers 5
How to get dir file list in Android 11
I want to write own lite file browser.
File API does not work for external storage now.
The release also offers improvements to scoped storage, which makes it easier for developers to migrate to using this storage model.
I don’t understand how use scoped storage for access to /sdcard.
4 Answers 4
If you’re looking for a file picker experience, Storage Access Framework is your only option now. Below code let’s you pick up multiple files. If you want directory level selection, you can use ACTION_OPEN_DOCUMENT_TREE intent.
Additionally, you can request a special all files access to MediaStore.Files from Google Play Console. More on Android 11 storage changes.
Edit:
If you want to implement a file browser like experience in Android 29+, here is a proposed idea that I personally haven’t tried out but should work. It won’t be an optimal experience but would closely resemble a file browser.
- If API = requestLegacyExternalStorage=»true» if API == 29).
- If API > 29, ask for all files access from Google Play Console.
- Put MANAGE_EXTERNAL_STORAGE flag in Manifest
- Prompt user to allow all files access by opening the settings with ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION intent.
- Query all files from MediaStore.Files along with RELATIVE_PATH
- Relative path + display name will give you something like DCIM/Vacation/IMG_1234.jpg .
- Create a tree (more like a forest) out of all the relative path and show it in UI.
I recently wrote an Android file/folder chooser library in Java that targets API 29+ (e.g., the Android OS 10/11 changes). It is called the Android File Picker Light. The idea is to have a barebones file/directory selector that displays minimalistic information about the local file system without pulling in too much multimedia processing to do things like visually display media files and image thumbnails. Some code that I used to get at the initial poster’s question of how to enumerate files on the local disk (or SD card) via traditional Unix-V style paths is seen here (for example, and elsewhere there). It still works well on Android OS 10 (API 29) active as of December, 2020.
The links provided above should get you started. The source to my library project is available freely under the GPL. There is also some Google-sanctioned official source code to document the implementation of a custom file storage provider on their GitHub repos. One thing to keep in mind is that the Android API is effectively trying to generalize the interface to a «file content» so that we have a common mechanism for online indexing (like a DropBox link) and the local file system. This is well intentioned enough until one sees how much more complicated it becomes to perform simple, routine filesystem operations from the local disk or integrated SD card. Eventually us avid developers may have to be led en mass to petition the Android official documentation writers for better pointers to handle these formerly common cases of file system access :).
With this point in mind, I want to iterate on a couple of distinguishing issues to the new scoped storage changes that others may run into writing their own custom code. I hope this saves developers some future stumbling around with what seem to be common issues (to me) not adequately addressed in some of the under documented parts of the Android developer docs about scoped storage. It is possible that as Android 11 starts to occupy more live devices in the wild these problems I had will get integrated into the office docs. For now, I suggest the following few reference points:
- It is now tricky to get filesystem data like POSIX style permissions out of the newly restricted Android API changes using more standard (portable even) Java I/O, or NIO, calls. Based on what I was able to get out of my Android 10 OS development device, it seems that the system gives special permissions when you try to access MatrixCursor type column data by creating a subclass of DocumentsProvider . This is all to say that the new changes will return legit System-V-Unix style traditional paths (like /storage/0/self/primary/Pictures/Screenshots ), but doesn’t seem to like to honor them as a way to refer to these files explicitly outside of the special file provider inheritance scheme (sigh.). The only way I found to extract POSIX style permissions from a valid Java File instance enumerated from a hardcoded path is referenced in my library code seen inline here. Your milage may vary.
- The move to scoped storage imposed whenever Android 11 becomes common place on devices is going to introduce some additional constraints on selecting files by path. In particular, the DocumentsProvider subclass I had to create in my library is capable of returning handles to the Unix-type paths for Java files (for local file system cases), or otherwise to Uri objects for abstract file type references that do not conform to this specification. In general, and so moving forward with the new API requirements, the subclassed DocumentsProvider is responsible for servicing the actual file data (as a String or Byte[] array typically), and currently at the same time as when users can enumerate these files to select by their familiar path names. Needless to say, this complicates the usage pattern for developers that want the user to select the file by its name a long while before the file contents are ever read to process by the program.
- There are some legacy style AndroidManifest.xml options that can be used with current Android 10 devices to bypass the scoped storage requirements. Read about them in my compiled links listed here (library Markdown reference). These legacy behavior enablers include the android:requestLegacyExternalStorage and android:preserveLegacyExternalStorage application tag options. Notice that this type of compatibility for pre-11 OS devices has the strange counterintuitive downside of requiring a new MinSdkVersion setting in the local application build.gradle file (with Android Studio).
- There is some funny, again under documented, behavior going on with how to (which to use) refer to hardcoded file system path references. In my library (for example), this syntax is used. In general, my intuition is that the new Android 11 scoped storage changes make historical access patterns convoluted and clearly dated to the point of deprecation. By this I mean that appCtx.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) may return a NULL Java File handler, but a hardcoded path like new File(«/storage/self/primary/Documents») can still be made to work if we configure the XML file path names correctly for use with the AndroidManifest file, e.g.:
I apologize for the long winded commentary I just gave. I hope this saves people some time in the future. — M
Источник
Android: List External Storage Files
As you can see, the TextView is wrapped in a ScrollView to handle a large number of files.
Step 4:
Open the MainActivity.kt and add a listFiles and a listExternalStorage function as shown below:
The listFiles receives a directory and recursively list files in that directory. If the newly found File is a directory, it’s sub-files are listed recursively. If it is an actual file, the absolute path of that file is appended to the txtFiles TextView .
Step 5:
Add the requestCode variable, the list function and override the onRequestPermissionsResult function as shown below:
Step 6:
Add the rxjava dependency to the build.gradle (Module: app) .
After adding these two dependencies your build.gradle should look like this:
After saving the changes, synchronize the project to download the dependencies.
Step 7:
Modify the MainActivity.kt as shown below:
Notice that there is a disposable instance variable which is used to dispose the RxJava resources in the onPause method and in the onComplete (the third block in the subscribe method call) lambda expression. Now there is a FileLister publisher which receives the parent directory to traverse and publish the files to the subscriber. Once the traversal is completed (after the recursive method call), the publisher calls the onComplete method to let the subscriber know that the process is completed.
The listExternalStorage function executes the publisher in a separate thread and appends the result to TextView in the main thread.
Though we can list all the files from the external storage, it is not recommended to do so unless otherwise there is a valid reason behind it. You can find the source code of this project at the GitHub repository.
If you have any questions, feel free to comment below.
Источник
android, how to get directory listing?
Just a quick question, how to I get a list of directories inside a specified directory.
now I’d need to get the list of directories that are inside the «path» directory.
5 Answers 5
Something like that (add null checking, exceptions etc..)
I know this has already been answered but I noticed it’s missing another, arguably simpler option. So I’m including it for future reference.
This code saves you having to use a for loop.
Android File API reference here
( Sorry, I couldn’t test. ) (it must import «android.app.«, «android.os.«, «android.widget.«, «android.view.«, «android.view.View.«, «java.io.«
This example will dir list folder and add to list then display as toast. You need to add permission Read External File, if not, your app will crash when trying to dir «/sdcard».
Not the answer you’re looking for? Browse other questions tagged java android or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
How to list files in an android directory?
Here’s my code so far:
Yet while I do have files in that dir, it returns me list.length = 0. any ideas?
12 Answers 12
In order to access the files, the permissions must be given in the manifest file.
I just discovered that:
new File(«/sdcard/»).listFiles() returns null if you do not have:
set in your AndroidManifest.xml file.
Well, the AssetManager lists files within the assets folder that is inside of your APK file. So what you’re trying to list in your example above is [apk]/assets/sdcard/Pictures.
If you put some pictures within the assets folder inside of your application, and they were in the Pictures directory, you would do mgr.list(«/Pictures/») .
On the other hand, if you have files on the sdcard that are outside of your APK file, in the Pictures folder, then you would use File as so:
And relevant links from the docs:
File
Asset Manager
In addition to all the answers above:
If you are on Android 6.0+ (API Level 23+) you have to explicitly ask for permission to access external storage. Simply having
in your manifest won’t be enough. You also have actively request the permission in your activity:
Your path is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list() or you enumerate files on your SD card by means of File.list()
Updated working method
My minSdkversion is 21, so I’m using ContextCompat.checkSelfPermission() method to grant permissions apart from also adding the in manifest. Thus, to get rid of the NullPointerException in spite of having files in your targeted directory, grant permissions as follows:-
MainActivity.java
There are two things that could be happening:
- You are not adding READ_EXTERNAL_STORAGE permission to your AndroidManifest.xml
- You are targeting Android 23 and you’re not asking for that permission to the user. Go down to Android 22 or ask the user for that permission.
If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn’t work, it’s worth reading this answer:
I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won’t continue to work in future versions.
Источник
How do I list all file in a directory in android 10 using Android Studio?
My current code uses:
The problem is that the array comes up as blank for anything outside:
From what I read online this no longer works with android 10+. So how would I list all files in a certain directory? (Making a file explorer as part of an App)
5 Answers 5
Just add this line of code to your manifest in the application tag.
android: requestLegacyExternalStorage= «true»
Yes, With old code it won’t work. Here i found the solution
In the above code, I written for images only if you want any other files audio video you need to replace Images with Audio and Video . etc
Note: if you convert Uri to file or string, then you can’t use those files. You will get an error in android 10
for get fileNames,try this.
What you described is valid.
Use Storage Access Framework to be able to list all directories.
Base on https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory(), To improve user privacy, direct access to shared/external storage devices is deprecated Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.
In my case,I need to find images or any kind of documents like .docx,.xls file on user’s device so I’m using ACTION_OPEN_DOCUMENT like bellow:
Источник