【问题标题】:FileProvider.getUriForFile is throwing StringIndexOutOfBoundsExceptionFileProvider.getUriForFile 正在抛出 StringIndexOutOfBoundsException
【发布时间】:2019-06-20 12:11:06
【问题描述】:

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

源代码如下所示:

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() 运行调试器。相关代码 sn-p 如下(第 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/sdcard,这也是path 的确切值,因此抛出异常也就不足为奇了。

我做错了什么?

更新:

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

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

应替换为:

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

【问题讨论】:

  • 您的file 不是文件。这是一个目录。您需要传递一个指向特定文件的File 对象。

标签: java android android-intent android-fileprovider


【解决方案1】:

getUriForFile 的第三个参数应该是您的文件路径和文件名。 Here is an docs, read it.

【讨论】:

  • 我已阅读文档,其中清楚地指出:“file - File: A File 指向您想要内容的文件名Uri。” java.io.File 可以是目录或文件。文档从不说它不应该是一个目录。不过,这确实是个问题,我会接受你的回答。
猜你喜欢
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多