Kotlin Update - December, 2022
Most answers above are okay but I wanted to add an updated version of the answer for developers in 2022 or later working with Kotlin. The code works on a fragment instead of an activity since one-activity apps are the modern Google-recommended pattern.
Launching the Video intent
First, we start by launching the intent. As of writing this answer, startActivityForResult
has been deprecated, and instead an activityResultLauncher
is used. Using MediaStore.Video.Media.EXTERNAL_CONTENT_URI
on the intent throws some warnings so I will avoid using it here. Here is the new version of the code compared to the old one;
Old way
val intent = Intent(Intent.ACTION_PICK,MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
intent.type = "video/*";
startActivityForResult(intent, REQUEST_VIDEO_CODE)
New Way
val intent = Intent(Intent.ACTION_PICK, null)
intent.type = "video/*"
resultLauncher.launch(intent)
And then create a result launcher
private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val data: Intent? = result.data
// For null safety, make sure data is not null
if (data == null) {
Log.d("TAG", "Data returned is null")
return@registerForActivityResult
}
val videoUri: Uri = data?.data!!
val videoPath = parsePath(videoUri)
// Do something with either the path or video Uri as needed
}
}
Getting file path
Once you get the video Uri, you can perform whatever action you want with it but for the benefit of the question, we will get the path. The parsePath()
method is as shown below.
private fun parsePath(uri: Uri?): String? {
val projection = arrayOf(MediaStore.Video.Media.DATA)
val cursor: Cursor? = requireActivity()
.contentResolver.query(uri!!, projection, null, null, null)
return if (cursor != null) {
val columnIndex: Int = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)
cursor.moveToFirst()
val path = cursor.getString(columnIndex)
cursor.close() // Make sure you close cursor after use
path
} else null
}