Home > Enterprise >  Android Kotlin - Glide listener download image as Bitmap to variable and make placeholder onerror
Android Kotlin - Glide listener download image as Bitmap to variable and make placeholder onerror

Time:09-29

I need to download an image and keep it as variable to put it into a notification:

.setLargeIcon(bitmap)

This is the code, I hope, it's clear by the comments what I try:

        var bitmap = BitmapFactory.decodeResource(this@MainActivity.resources, R.drawable.notif_smiley) // create placeholder bitmap

        val requestOptions = RequestOptions()
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)

        bitmap = Glide.with(this@MainActivity)
            .asBitmap()
            .load(imgurl)
            .listener(object : RequestListener<Bitmap> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    // just dont do anything, keep the placeholder bitmap
                    return false
                }
            })
            .apply(requestOptions)
            .submit()
            .get()


        binding.contentMain.testingGlide.setImageBitmap(bitmap) // this is just for easy testing

I get all kind of error, I tried this based on an answer but there the bitmap goes directly into a view, please help :D

CodePudding user response:

Inside your load failed method you're not setting any image so try changing that also try adding the onerror() method below code implementation should fix it

try{
     lateinit var bitmap:Bitmap
           bitmap =  Glide.with(context)
                    .asBitmap()
                    .placeholder(R.mipmap.avengerswallp)
                    .load(imgUri)
                    .error(getnothumb())
                    .listener(object : RequestListener<Bitmap>{
                        override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
                            bitmap = myPlaceHolderBitmap
                            return true
                        }

                        override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                            return false
                        }
                    }).submit().get()
}
catch(ex:Exception)
{
}
  • Related