'How to display installed app icon in jetpack compose

In jetpack compose, you can display drawables easily with the Image composable like this:

Image(painter = painterResource(id = R.drawable.my_drawable))

I'm building an app that requires listing all the apps on the device and I need to display their icons. I managed to get the icons using the PackageManager class:

val packageManager = context.packageManager
val installedPackages = packageManager.getInstalledPackages(0)
val packageInfo = installedPackages[0]
val iconId: Int = packageInfo.applicationInfo.icon

Then:

Image(painter = painterResource(id = iconId))

But the app crashes everytime. I don't know where the problem is? Any Idea? Thanks

android.content.res.Resources$NotFoundException: Resource ID #0x7f030001


Solution 1:[1]

If you're using the Coil library, rememberImagePainter will accept an Any? as its data argument, allowing you to use the Drawable returned from the PackageManager, like so:

  Image(
    painter = rememberImagePainter(
      data = LocalContext.current.packageManager.getApplicationIcon("com.package.example")
    )
  )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lase