Android Scope Storage: Get Filename and Mime Type From Uri

Assuming you have the media/file uri based on MediaStore.MediaColumns._ID.

On KITKAT / API 19 and above.

val file = DocumentFile.fromSingleUri(context, uri)if (file != null) {    Timber.d("uri=$uri, filename=${file.name}, mimeType=${file.type}")}

No KitKat Restrictions

class MediaFile private constructor(context: Context, uri: Uri) {    lateinit var displayName: String    lateinit var mimeType: String    companion object {        fun fromUri(context: Context, uri: Uri): MediaFile? {            return try {                MediaFile(context, uri)            }            catch (e: FileNotFoundException) {                null            }        }    }    init {        val contentResolver = context.contentResolver        val projection = arrayOf(            MediaStore.MediaColumns.DISPLAY_NAME,            MediaStore.MediaColumns.MIME_TYPE        )        contentResolver.query(uri, projection, null, null, null).use { cursor ->            if (cursor == null) throw FileNotFoundException(uri.toString())            if (cursor.moveToFirst()) {                val displayNameIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)                val mimeTypeIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE)                displayName = cursor.getString(displayNameIndex)                mimeType = cursor.getString(mimeTypeIndex)            }        }    }}
val file = DocumentFile.fromSingleUri(context, uri)if (file != null) {    Timber.d("uri=$uri, filename=${file.displayName}, mimeType=${file.mimeType}")}else {    Timber.d("File not found: $uri")}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.