Michael Gierer
Michael Gierer

Reputation: 453

java/android - Cannot access files on SD card

I'm developing an Android App for Android 8.0 where I need to open/read and delete files from the external storage / SD card.

My problem is, that File file[] = directory.listFiles() returns NULL, but there is a file in the directory.

Here is the debugger view from my app:

Debugging App

As you can see, I'm getting the filepath as an URI through an Intent request (variable resource). Currently, the folder Test on the SD card is selected.

Then I want to get all the files in this directory, but the function listFiles() returns always NULL! But there is 1 image in the folder:

Actual content of the folder

Interestingly, this code works on Android 4.4, 5.0, 6.0 and 7.0 but not on Android 8!

The permissions are set in Manifest.xml and are requested/checked on each startup:

Requested Permissions

Note: Android only shows 1 permission request when starting the app, but shouldn't it request 2 permissions?

I hope someone of you can help me solve the problem.

Best regards, Michael

Upvotes: 1

Views: 1572

Answers (1)

Solution:

Try to use:

DocumentFile directory = DocumentFile.fromTreeUri(context, Uri.parse(resources.getUri()));

Instead of:

File directory = new File(resources.getPath());

Also See

ContextCompat.getExternalFilesDirs solves the access error

Universal Truth:

1. Android 7.0 provides a simplified API to access external storage dirs.

Scoped Directory Access In Android 7.0, apps can use new APIs to request access to specific external storage directories, including directories on removable media such as SD cards...

For more information, see the Scoped Directory Access training.


2. Android O changes.

Starting in Android O, the Storage Access Framework allows custom documents providers to create seekable file descriptors for files residing in a remote data source...

Permissions, prior to Android O, if an app requested a permission at runtime and the permission was granted, the system also incorrectly granted the app the rest of the permissions that belonged to the same permission group, and that were registered in the manifest.

For apps targeting Android O, this behavior has been corrected. The app is granted only the permissions it has explicitly requested. However, once the user grants a permission to the app, all subsequent requests for permissions in that permission group are automatically granted.

For example, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE...

Hope it helps.

Upvotes: 1

Related Questions