ThiagoYou
ThiagoYou

Reputation: 318

Kotlin how to get and open a video

New to Kotlin and i'm trying to simple get any video from gallery and open into device's default app player.

My function to get all videos. It seens to work well, but the returned Uri is like 'content://...', i don't know if this is the right or it should be something like 'file://...'

private val videos = mutableListOf<Uri>()

private fun getAllVideos() {
    val uriExternal = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
    val projection = arrayOf(MediaStore.Video.Media._ID)

    contentResolver.query(uriExternal, projection, null, null, null)?.use { cursor ->
        while (cursor.moveToNext()) {
            val videoUri = Uri.withAppendedPath(uriExternal, "" + cursor.getString(0))
            videos.add(videoUri)
        }
    }
}

Then i try to open the Uri like this, but i always get an error from the player and nothing works.

val intent = Intent(Intent.ACTION_VIEW).apply {
    data = videos.first()
    type = "video/*"
}

startActivity(intent)

I searched but dont found any updated tutorial that don't use "MediaStore.Video.Media.DATA" (it's deprecated now). Something i'm doing wrong?

Upvotes: 1

Views: 1687

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006614

but the returned Uri is like 'content://...', i don't know if this is the right

Yes, it is.

Then i try to open the Uri like this, but i always get an error from the player and nothing works.

First, either remove the type or use the correct MIME type. Do not use a wildcard.

Second, add FLAG_GRANT_READ_URI_PERMISSION to the Intent. Without it, the other app has no rights to access the content.

Also, make sure you only go through that code if there is at least one element in the list, as otherwise your first() call will throw an exception.

Upvotes: 1

Related Questions