Search code examples
androidkotlinandroid-roommobile-development

What is a proper way to store drawables in the Room Library? Android, Kotlin, XML


I'm beginner in Android development and now developing my application that helps me to keep track of my personal finances. All my categories (food, shopping, etc) have a displayed color and icon (XML drawable) that should be stored inside Room database: Category example

What datatype or method should I use in order to store those icons inside my Room database?

This is my current implementation of the Category Entity:

@Entity(tableName = "category")
data class Category(
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null,
    @ColumnInfo(name = "name")
    var name: String?,
    @ColumnInfo(name = "expanses")
    var expanses: Double?,
    @ColumnInfo(name = "icon")
    var icon: Int?,
    @ColumnInfo(name = "color")
    var color: Int?)

I'm using this Icon Picker in my app.


Solution

  • For anyone, who are interested, here is my own solutions:

    1. Instead of storing icons as Bitmap or using any other type converters, I can store the names of my Drawables inside my database and use resources.getIdentifier("myIconName", "drawable", Context.packageName) in order to retrieve them whenever I want. More information in this Reddit thread

    2. As I use this Icon Picker, I can instead store icon IDs (do not confuse with resource ID), which I specify inside icons.xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <icons width="24" height="24" xmlns:android="http://schemas.android.com/apk/res/android">
    <category id="0" name="category_shapes">
        <icon id="0" tags="shape,circle" path="M12 2A10 10 0 0 0 2 12A10 10 0 0 0 12 22A10 10 0 0 0 22 12A10 10 0 0 0 12 2Z"/>
        <icon id="1" tags="shape,triangle,three" path="M1 21H23L12 2"/>
        <icon id="2" tags="shape,square,four" path="M3 3V21H21V3"/>
        <icon id="3" tags="shape,pentagon,five" path="M12 2.5L2 9.8L5.8 21.5H18.2L22 9.8L12 2.5Z"/>
        <icon id="4" tags="shape,octagon,eight" path="M15.73 3H8.27L3 8.27V15.73L8.27 21H15.73L21 15.73V8.27"/>
    </category>
    <category id="1" name="category_stars">
        <icon id="5" tags="shape,star,three" path="M12 2.6L9 12.4L2 19.9L12 17.6L22 20L15 12.5L12 2.6Z"/>
        <icon id="6" tags="shape,star,four" path="M12 1L9 9L1 12L9 15L12 23L15 15L23 12L15 9L12 1Z"/>
        <icon id="7" tags="shape,star,five" path="M12 17.27L18.18 21L16.54 13.97L22 9.24L14.81 8.62L12 2L9.19 8.62L2 9.24L7.45 13.97L5.82 21L12 17.27Z"/>
        <icon id="8" tags="shape,star,eight" path="M2.2 16.06L3.88 12L2.2 7.94L6.26 6.26L7.94 2.2L12 3.88L16.06 2.2L17.74 6.26L21.8 7.94L20.12 12L21.8 16.06L17.74 17.74L16.06 21.8L12 20.12L7.94 21.8L6.26 17.74L2.2 16.06Z"/>
    </category>
    </icons>