android get file 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.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 ->
println( getFileExtension(uri)!! )
}
}
}
}
companion object{
const val PICK_ANY_FILE = 100
fun Context.getFileExtension(uri: Uri): String? = when (uri.scheme) {
ContentResolver.SCHEME_FILE -> File(uri.path!!).extension
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))
else null
}.also { cursor.close() }
}
} catch (e: Exception) {
null
}
}
}