androidimageandroid-roomassets

How do I include image assets in an Android app and reference them from a Room database


Currently I have a data class defined, included the image as a resource using the resource manager and use in a composable component, as follows:

data class Picture(
    val name: String,
    val imageId: Int = -1,
)

val picture = Picture(name = "Cake", imageId = R.drawable.cake)

@Composable
fun PictureItem(picture: Picture) {
    Card {
        Box(
            modifier = modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = modifier.padding(16.dp),
            ) {
                Image(
                    painterResource(id = picture.imageId),
                    contentDescription = picture.name
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = product.name)
            }
        }
    }
}

I am trying to learn how to move the data into Room and was wondering how to handle the images when we do that. I imagined replacing the id reference with something that points to an image file but could not figure out how to approach it correctly.


Solution

  • Don't use resources for this. Resource ids are assigned at each compile time and are not stable- compiling the app with any changes could lead to a totally different arrangement of ids. Instead, use assets and open it from assets, with the pathname of the asset in the database instead of a resource id.

    You could also use resources with names and do by name lookups, but that's not really recommended or efficient.