ContentResolver - how to get file name from Uri

后端 未结 7 553
误落风尘
误落风尘 2020-12-30 03:38

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

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

I

7条回答
  •  心在旅途
    2020-12-30 03:49

    For anyone using Kotlin who has the same problem, you can define an extension method to get the file name and size (in bytes) in one fell swoop. If it is unable to retrieve the fields, it returns null.

    fun Uri.contentSchemeNameAndSize(): Pair? {
        return contentResolver.query(this, null, null, null, null)?.use { cursor ->
            if (!cursor.moveToFirst()) return@use null
    
            val name = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            val size = cursor.getColumnIndex(OpenableColumns.SIZE)
    
            cursor.getString(name) to cursor.getInt(size)
        }
    }
    

    Use it thusly

    val nameAndSize = yourUri.contentNameAndSize()
    // once you've confirmed that is not null, you can then do
    val (name, size) = nameAndSize
    

    It might throw an exception, but it hasn't ever done so for me (as long as the URI is a valid content:// URI).

提交回复
热议问题