Android – ContentResolver – how to get file name from Uri

androidandroid-contentresolver

I call startActivityForResult with Intent ACTION_GET_CONTENT. Some app returns me data with this Uri:

content://media/external/images/media/18122

I don't know if it is image or video or some custom content. How do I use ContentResolver to get the actual file name or content title from this Uri?

Best Answer

@Durairaj's answer is specific to getting the path of a file. If what you're searching for is the file's actual name (since you should be using Content Resolution, at which point you'll probably get a lot of content:// URIs) you'll need to do the following:

(Code copied from Durairaj's answer and modified)

        String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
        Cursor metaCursor = cr.query(uri, projection, null, null, null);
        if (metaCursor != null) {
            try {
                if (metaCursor.moveToFirst()) {
                    fileName = metaCursor.getString(0);
                }
            } finally {
                metaCursor.close();
            }
        }

The main piece to note here is that we're using MediaStore.MediaColumns.DISPLAY_NAME, which returns the actual name of the content. You might also try MediaStore.MediaColumns.TITLE, as I'm not sure what the difference is.