How to load images from the internet into a widget with Jetpack Glance?

1.7k Views Asked by At

I have a widget developed with Jetpack Compose and with the Jetpack Glance library, this widget is a LazyColumn list, in which I pass the information after making a query to the Room Database database.

enter image description here

To try to load the image I used Image() with the provider, passing it a string (which is the url of the image I want to load)

Image(
   modifier = GlanceModifier.size(50.dp),
   provider = ImageProvider(item.image),
   contentDescription = null
)

This didn't load the image and I tried to pass that image url to a bitmap, to load it with BitmapImageProvider(), but it didn't work. Is there a way to load a remote image to a widget using Jetpack Glance?

2

There are 2 best solutions below

8
On

I would recommend to check the ImageGlanceWidget sample code. The sample shows how to use WorkManager to load images from network and using URI or bitmaps to display them.

Loading images and doing background work with Glance/Widgets is tricky for now but we are improving this soon by supporting recomposition.

Here is an example of how it will look like in future releases of Glance https://gist.github.com/marcelpinto/6df5e3e6ca42c6a0bf34b9f4b6eb1cff

0
On

For your provider parameter, you can use the below function to pull the bitmap from file. The path parameter is where you saved the downloaded bitmap in your local storage.

Image(
   modifier = GlanceModifier.size(50.dp),
   provider = getImageProvider(LocalContext.current),
   contentDescription = null
)
private fun getImageProvider(path: String): ImageProvider {
    return if (path=="") { /*dummy image to return if path is blank*/
        ImageProvider(R.drawable.ic_launcher_background)
    } else {
        val bitmap = BitmapFactory.decodeFile(path)
        ImageProvider(bitmap)
    }
}
/*path parameter example*/
val bitmapFile = File(fileDir, fileName)
val uri = Uri.fromFile(outputFile)
val path = uri.path ?: ""