![](/img/trans.png)
[英]FileProvider.getUriForFile context throwing NullPointer exeption
[英]FileProvider.getUriForFile is throwing 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)
在application
標簽內的AndroidManifest.xml
,我添加了以下內容:
<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
,它也是path
的確切值,因此也就不會拋出異常。
我究竟做錯了什么?
更新:
如下面的建議,傳遞的java.io.File
不應是目錄。 文檔是模棱兩可的,永遠不要明確地說出來。 解決方法是“手動”創建uri。 從而
intent.setData(FileProvider.getUriForFile(this, authority, file));
應替換為:
intent.setData(Uri.parse("content://" + file.getAbsolutePath()));
getUriForFile的第三個參數應該是帶有文件名的文件路徑。 這是一個文檔,請閱讀 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.