首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FileProvider.getUriForFile扔StringIndexOutOfBoundsException

FileProvider.getUriForFile扔StringIndexOutOfBoundsException
EN

Stack Overflow用户
提问于 2019-01-27 07:20:08
回答 1查看 1.1K关注 0票数 5

首先要提到的是,这里问题的答案没有帮助。

源代码如下所示:

代码语言:javascript
运行
复制
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正在抛出异常,下面是堆栈跟踪:

代码语言:javascript
运行
复制
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标记中,我添加了以下内容:

代码语言:javascript
运行
复制
        <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的内容如下:

代码语言:javascript
运行
复制
<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()运行调试器。相关代码片段如下(第633-688行):

代码语言:javascript
运行
复制
            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不应该是一个目录。文档是模棱两可的,从来没有明确地说过。解决办法是“手动创建uri”。因此

代码语言:javascript
运行
复制
intent.setData(FileProvider.getUriForFile(this, authority, file));

应改为:

代码语言:javascript
运行
复制
intent.setData(Uri.parse("content://" + file.getAbsolutePath()));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-27 08:12:34

第三个对getUriForFile,应该是您的路径,您的文件名。这是一个文档,读一读

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54385933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档