首页 > 解决方案 > FileProvider.getUriForFile 正在抛出 StringIndexOutOfBoundsException

问题描述

首先要提到的是,这里问题的答案无济于事。

源代码如下所示:

Intent intent    = new Intent("com.mycompany.action.PICK_FILE");
String authority = "com.mycompany.fileprovider";
File   file      = Environment.getExternalStorageDirectory();

intent.setData(FileProvider.getUriForFile(this, authority, file));

FileProvider.getUriForFile正在抛出异常,这是堆栈跟踪:

java.lang.StringIndexOutOfBoundsException: length=15; index=16
at java.lang.String.indexAndLength(String.java:500)
at java.lang.String.substring(String.java:1313)
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:687)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:377)

在标签AndroidManifest.xml内部,application我添加了以下内容:

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.mycompany.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" 
            />
        </provider>

的内容file_paths.xml如下:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="input_files"  path="." />
    <external-path name="output_files" path="MyAppName/" />
</paths>

output_files在此上下文中不使用路径。

我已经通过FileProvider.SimplePathStrategy.getUriForFile(). 相关代码片段如下(第 683-688 行):

            final String rootPath = mostSpecific.getValue().getPath();
            if (rootPath.endsWith("/")) {
                path = path.substring(rootPath.length());
            } else {
                path = path.substring(rootPath.length() + 1);
            }

rootPath被评估为/storage/sdcardwhich 也是 的确切值path,因此抛出异常也就不足为奇了。

我究竟做错了什么?

更新:

正如下面所建议的,passedjava.io.File不应该是一个目录。文档是模棱两可的,从不明确地说出来。解决方法是“手动”创建 uri。因此

intent.setData(FileProvider.getUriForFile(this, authority, file));

应替换为:

intent.setData(Uri.parse("content://" + file.getAbsolutePath()));

标签: javaandroidandroid-intentandroid-fileprovider

解决方案


getUriForFile 的第三个参数应该是带有文件名的文件的路径。这是一个文档,请阅读


推荐阅读