how to get file type from uri kotlin code example

Example: how to get file type from uri kotlin

class MainActivity : AppCompatActivity(){

  	override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // my_button = id in activity_main layout
        // need for call intent 
        my_button.setOnclickListener{
           val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
             addCategory(Intent.CATEGORY_OPENABLE)
             type = "*/*"
           }
          startActivityForResult(intent, PICK_ANY_FILE)
        }
    }
  
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
  super.onActivityResult(requestCode, resultCode, resultData)
  if (resultCode == RESULT_OK && resultCode == PICK_ANY_FILE) {
	 if (resultData != null) {
       		resultData.data?.also { uri ->
         	// usage for function
       		println( getFileExtension(uri)!! )
       }
     }
  }
}  
    

companion object{
	const val PICK_ANY_FILE = 100
 		/* get actual file name or extension */
        fun Context.getFileExtension(uri: Uri): String? = when (uri.scheme) {
            // get file extension 
            ContentResolver.SCHEME_FILE -> File(uri.path!!).extension
            // get actual name of file 
            //ContentResolver.SCHEME_FILE -> File(uri.path!!).name
            ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
            else -> null
        }

        private fun Context.getCursorContent(uri: Uri): String? = try {
            contentResolver.query(uri, null, null, null, null)?.let { cursor ->
                cursor.run {
                    val mimeTypeMap: MimeTypeMap = MimeTypeMap.getSingleton()
                    if (moveToFirst()) mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri))
                    // case for get actual name of file     
                    //if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    else null
                }.also { cursor.close() }
            }
        } catch (e: Exception) {
            null
        }
	}
}

Tags:

Misc Example