I am populating my images using coil in jetpack compose and the issue I face is that I am not able to programmatically identify if the url is no longer valid.
val imageUrl = "www.someinvalidurl.com"
val painter = rememberImagePainter(
data = imageUrl
)
Image(
painter = painter
)
The url was previously valid but is not valid anymore. Coil shows the default placeholder url but then I want to identify this failure and attempt to get an image from a different url. I have tried this,
if (painter.state is ImagePainter.State.Error) {
//failed so try to get an image from a different url
}
But the problem with this is that this block is called even for valid urls.
I am using the following version of coil :
implementation("io.coil-kt:coil-compose:1.4.0")
Is there a different right way of identifying invalid URLs in coil while using jetpack compose
Add a listener that checks for exceptions. In this sample, the file extension should be "jpg" but I removed the "g" to test that the image does not exist:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(intent)
setContent {
val imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jp"
val painter = rememberImagePainter(
data = imageUrl,
builder = {
this.listener(
onError = {request, ex ->
if ((ex as HttpException).response.code() == 400) {
// Image not found
}
}
)
}
)
Image(
painter = painter,
contentDescription = null
)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With