I get fatal exception when trying to run the following snippet of java code in android studio (API 30). I tried to follow these steps from 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
...
Probably the problem is with the context, but I don't know why. Here are some debug prints:
System.out.println(returnCursor);
-> android.content.ContentResolver$CursorWrapperInner@7cfe38a
System.out.println(nameIndex);
-> 2
CodePudding user response:
The Cursor
is positioned before the first row by default. Call moveToFirst()
on it before trying to read a value.
You might also consider using DocumentFile.fromSingleUri()
, then calling getName()
on the resulting DocumentFile
, which does the same thing as your code.