简体   繁体   中英

Get file name from Uri in Android

I have an Uri build using below code

final Uri fileUri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, docId);

that contains value:

content://com.android.externalstorage.documents/tree/primary%Sample/document/primary%Sample%2FMedia%2F.Hide%2FScreenshot_1615959401.png/children

Below is my code to access the name and mime type of file:

ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(fileUri, new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE}, null, null, null);
try {
        if (cursor != null && cursor.moveToFirst()) 
        {
          //Here cursor.moveToFirst() returns false
        }
    } catch(Exception e)
        {
           e.printStackTrace();
        }

I want to access the name of file like Screenshot_1615959401.png, mime type file like image/png from above Uri but cursor.moveToFirst() returns 0. Why record is not found even Uri is valid. Because I try to use this Uri to load image and ImageView is displaying the image correctly using above Uri.

Any Help would be highly appreciated as I spent lots of time googling and read on SO but didn't find any solution or root cause of it.

Below is my code to access the name and mime type of file:

That Uri is not for a document. It is for the roster of child documents for a document tree, where the tree is identified by docId . childDocumentsUri is the core of the name of the method that you are calling.

Why record is not found even Uri is valid

It is not valid for your desired action.

If you wish to build a Uri for a document, given a document ID and a tree, use buildDocumentUriUsingTree() , not buildChildDocumentsUriUsingTree() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM