[英]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.尝试在 Kotlin 中将Uri
图像文件转换为Bitmap
失败,并出现空指针异常。 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
}
var bitmap = remember { mutableStateOf<Bitmap?>(null)}
Here, bitmap.value
will be null
.在这里, bitmap.value
将为null
。
Image(
bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here
contentDescription = ""
)
Here, bitmap.value?.asImageBitmap()
will be null
, since bitmap.value
is null
.在这里, bitmap.value?.asImageBitmap()
将为null
,因为bitmap.value
为null
。 As a result, you will crash with a NullPointerException
as soon as you execute this code.因此,一旦执行此代码,您就会崩溃并出现NullPointerException
。
Eventually , bitmap.value
will not be null
, courtesy of your LaunchedEffect
, but that will take some time.最终, bitmap.value
不会是null
,由您的LaunchedEffect
提供,但这需要一些时间。 You need to rework your composable to be able to work prior to that point in time.您需要返工您的可组合物以便能够在该时间点之前工作。
bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here
not-null assertion is not a good way to handle this.非空断言不是处理这个问题的好方法。
Your possible options are either display Image with您可能的选项是显示图像
bitmap?.value?.asImageBitmap()?.let{ imageBitmap->
Image(...)
}
and wait for bitmap to be created while you display nothing并等待创建位图,而您什么也不显示
or display preferably a Composable
for loading or Image
with placeholder.或最好显示一个Composable
的加载或带有占位符的Image
。
if(bitmap.value!= null) {
Image(...)
} else {
// Your loading Composable
}
Another option is to use SubcomposeAsyncImage
which has slots for Loading, Error and Success Composable slots so you can pass your Composables inside these slots.另一种选择是使用SubcomposeAsyncImage
,它具有用于加载、错误和成功可组合插槽的插槽,因此您可以在这些插槽中传递您的可组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.