Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Coil Kotlin Uri to Bitmap throws null pointer exception

Trying to convert a Uri image file to Bitmap in Kotlin fails with a Null Pointer exception. How can I fix this?

var bitmap = remember {  mutableStateOf<Bitmap?>(null)}

LaunchedEffect(key1 = "tobitmap") {
    CoroutineScope(Dispatchers.IO).launch {
        bitmap.value = uriToBitmap(
            context,
            shoppingListScreenViewModel.state.value.imageUri
        )
    }
}

Image(
    bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here
    contentDescription = ""
)

private suspend fun uriToBitmap(context: Context, uri: Uri?): Bitmap {

    val loader = ImageLoader(context)
    val request = ImageRequest.Builder(context)
        .data(uri)
        .allowHardware(false) // Disable hardware bitmaps.
        .build()

    val result = (loader.execute(request) as SuccessResult).drawable
    val bitmap = (result as BitmapDrawable).bitmap

    val resizedBitmap = Bitmap.createScaledBitmap(
        bitmap, 80, 80, true);

    return resizedBitmap
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var bitmap = remember {  mutableStateOf<Bitmap?>(null)}

Here, bitmap.value will be null.

Image(
    bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here
    contentDescription = ""
)

Here, bitmap.value?.asImageBitmap() will be null, since bitmap.value is null. As a result, you will crash with a NullPointerException as soon as you execute this code.

Eventually, bitmap.value will not be null, courtesy of your LaunchedEffect, but that will take some time. You need to rework your composable to be able to work prior to that point in time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading