java - 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/sdcard
which 也是 的确切值path
,因此抛出异常也就不足为奇了。
我究竟做错了什么?
更新:
正如下面所建议的,passedjava.io.File
不应该是一个目录。文档是模棱两可的,从不明确地说出来。解决方法是“手动”创建 uri。因此
intent.setData(FileProvider.getUriForFile(this, authority, file));
应替换为:
intent.setData(Uri.parse("content://" + file.getAbsolutePath()));
解决方案
getUriForFile 的第三个参数应该是带有文件名的文件的路径。这是一个文档,请阅读。
推荐阅读
- delphi - 以编程方式更改快捷方式图标
- javascript - 锚点href vs 角度路由器链接
- javascript - 如何从 javascript 中的创建订阅 API 调用中检索 Stripe 订阅 ID
- python - Selenium:通过'option selected value'选择,默认时不存在
- docker - Docker compose 找不到本地包
- android - 将android生成的文件保存在运行模拟器的电脑上
- ios13 - iOS13不支持后台更新通知?
- php - PHP preg_match 正则表达式重定向网址
- vim - 为什么 UltiSnips 列出的可用片段不起作用?
- r - 在不同系列的线性模型中循环多个变量组合的问题