How to handle image not found error in Glide V4

Viewed 2385

I tried to handle image not found (404) error in Glide, but it doesn't compile :

Glide.with(this@ImageActivity)
                        .addDefaultRequestListener(
                                object:RequestListener<Drawable> {
                                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                                        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                    }

                                    override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                                        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                    }

                                }

                        )
                        .load(imageURL).apply(requestOptions)
                        .into(imageview)

But compiler raises this error on object:RequestListener :

Type mismatch: inferred type is but RequestListener! was expected

3 Answers

If you want to use addDefaultRequestListener, you need to use Any instead of Drawable

Glide.with(context).addDefaultRequestListener(object : RequestListener<Any> {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: com.bumptech.glide.request.target.Target<Any>?, isFirstResource: Boolean): Boolean {
            }

            override fun onResourceReady(resource: Any?, model: Any?, target: com.bumptech.glide.request.target.Target<Any>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
            }

        })

You have to use submit() like this -

Glide.with(this@ProfileActivity).load(imageURL).into(imageview)
              .listener(object : RequestListener<Drawable> {
                  override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                      //TODO handle error images while loading photo
                      return true
                  }

                  override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                      //TODO use "resource" as the photo for your ImageView
                      return true
                  }

              }).submit()

You can use Glide simply with placeholder() method. You can use the following method.

private fun fetchImage(imageView: ImageView, url: String){
    Glide
        .with(this)
        .load(url)
        .centerCrop()
        .placeholder(R.drawable.ic_menu_camera)
        .into(imageView)
}
Related