David David - 2 months ago 72
Android Question

Android getUriForFile IllegalArgumentException

My code for sending a file with an Intent doesn't work with all file sources and I could not find the solution yet:

My app is registered for opening files, so when I select a file in ES File Explorer the intent looks like this:


when selecting the same file in Asus File Manager I get following intent:


This is my code:

// With this path it works. Path example being sent by e.g ES File Explorer
String fileName = "/storage/emulated/0/backups/apps/PDFViewer.apk";
// with this path it doesn't. This path is sent by Asus File Explorer
fileName = "/file/sdcard/backups/apps/PDFViewer.apk";
final Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
installIntent.setData(getUriForFile(context, "com.myapp.fileprovider", new File(fileName)));

I also tried new File("/file/sdcard/backups/apps/PDFViewer.apk").exists(); what returns false.

The xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external" path="/"/>

And the provider in the manifest:

android:resource="@xml/file_provider_paths" />

The exception:

11-02 12:21:09.004: E/ACRA(9807): com.mycompany.myapp fatal error : Failed to find configured root that contains /file/sdcard/PDFViewer.apk
11-02 12:21:09.004: E/ACRA(9807): java.lang.IllegalArgumentException: Failed to find configured root that contains /file/sdcard/PDFViewer.apk
11-02 12:21:09.004: E/ACRA(9807): at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(SourceFile:711)
11-02 12:21:09.004: E/ACRA(9807): at android.support.v4.content.FileProvider.getUriForFile(SourceFile:400)

What am I missing?


The problem was using getUriForFile for file system paths and also for File Provider paths that actually must be used with a content resolver, so the solution was following:

            Uri uri;
            if (ContentResolver.SCHEME_CONTENT.equals(fileUri.getScheme())) {
                uri = new Uri.Builder()
            } else {
                uri = getUriForFile(context, "com.myapp.fileprovider", new File(fileUri.getPath()));