rot8
rot8

Reputation: 335

Save Images in Room Database

I want to save small images in my room database and I have two issues:

  1. How do I save an image in my database?
  2. How do I save multiple images in my database?

I tried saving a bitmap in the way recommended by the developers page (https://developer.android.com/training/data-storage/room/defining-data)

@Parcelize
@Entity(tableName = "image_table")
data class ImgMod(

    @PrimaryKey(autoGenerate = true)
    var invoiceId: Long = 0L,

    @ColumnInfo(name = "image")
    var single_img: Bitmap?
): Parcelable

However, I receive the following error:

Cannot figure out how to save this field into database. You can consider adding a type converter for it.

Secondly, I would like to save multiple images in one database entry. But I receive the same error with the following snippets:

    @ColumnInfo(name = "imageList")
    var img_list: ArrayList<BitMap>

or decoded bitmap as a String

    @ColumnInfo(name = "imageList")
    var decoded_img_list: ArrayList<String>

I am sorry if this is a very basic question. But how do I have to configure the database/process the data to an image list?

Thank you in advance, rot8

Upvotes: 3

Views: 6435

Answers (1)

Some random IT boy
Some random IT boy

Reputation: 8457

A very simple way to get images into the database (although I personally discourage it) would be to base-64 encode the bitmaps into a String and put it into a row of the database.

Take in account that bitmaps are very memory heavy; and base64 encoding something increases it's size some more so be careful when loading a bunch of images... I do also think Room and SQLite supports binary data as blobs, so you could just declare a column as ByteArray and it should just work.

What I've been doing in my projects is to write them into the internal or external storage of my app and then store the reference Uri as a String to later be able to retrieve the image from disk.

Something that I discourage even more is to stuff more than one value per row; having a list of stuff inside a coulmn in SQL is definetely not a pattern you should follow. Creating a "join" table should be simple enough or simply an extra column you could use to group them by should be easy enough, right?

Upvotes: 7

Related Questions