当我尝试在 android studio (API 30) 中运行以下 java 代码 fragment 时,出现致命异常。我尝试按照 https://developer.android.com/training/secure-file-sharing/retrieve-info 中的步骤进行操作
Uri selectedImageUri = data.getData();
if (selectedImageUri != null) {
Cursor returnCursor = requireContext().getContentResolver().query(selectedImageUri,
null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
System.out.println(returnCursor.getString(nameIndex));
}
E/AndroidRuntime: FATAL EXCEPTION: main
...
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1656054214, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/raw:/storage/emulated/0/Download/1.jpg flg=0x1 }} to activity {com.bonmanager/com.bonmanager.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
...
Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
...
可能问题出在上下文上,但我不知道为什么。以下是一些调试打印:
System.out.println(returnCursor);
-> android.content.ContentResolver$CursorWrapperInner@7cfe38a
System.out.println(nameIndex);
-> 2
最佳答案
默认情况下,光标
位于第一行之前。在尝试读取值之前对其调用 moveToFirst()
。
您还可以考虑使用 DocumentFile.fromSingleUri()
,然后对生成的 DocumentFile
调用 getName()
,这会执行相同的操作作为您的代码。
关于java - 尝试从 URI 获取文件名时出现致命的运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70251415/