Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fatal runtime exception when trying to get filename from URI

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading