androiduser-interfaceandroid-jetpack-composeandroid-jetpackandroid-gallery

Cannot Get Image from Gallery in Jetpack Compose


Cannot get image from gallery. Want to get images from gallery and display it. I am using coil library for displaying image.

var images by remember { mutableStateOf(listOf<Uri>()) }
    val galleryLauncher =
        rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) {
            images = it
        }
    Column() {
        Button(
            onClick = {
                galleryLauncher.launch("image/*")
            }
        ) {
            Text(text = "Get images")
        }
        LazyColumn(content = {
            items(images.size){ uri ->
                AsyncImage(model = uri, contentDescription = null)
            }
        })
    }

Solution

  • the problem is your are using the wrong items function in your lazyColumn. the one you are using takes an int as a parametre and then it gives an Int to the body not a uri.:

        LazyColumn(content = {
            items(images.size){ Int->
                AsyncImage(model = Int, contentDescription = null)
            }
        })
    

    you should use the other Items function from androidx.compose.foundation.lazy.items and your code should something like this:

    var images by remember { mutableStateOf(listOf<Uri>()) }
    val galleryLauncher =
        rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) {
            images = it
        }
    Column() {
        Button(
            onClick = {
                galleryLauncher.launch("image/*")
            }
        ) {
            Text(text = "Get images")
        }
        LazyColumn(content = {
            items(images){ uri ->
                AsyncImage(model = uri, contentDescription = null)
            }
        })
    }