0

How to save List<List<Bitmap>> to room database? Want to save List<List<Bitmap>> to room database, but it gives error:

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

How to add a type converter for it?

@Entity(tableName = "items")
data class Item(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    var image: List<List<Bitmap>>? = null,
)
Jorpy
  • 55
  • 1
  • 6

1 Answers1

0

This won't be effective for large images. You don't want megabytes of data in each row of your database. If the images are large, save them as files and put just the file names in your database.

But assuming these are tiny images:

Follow the instructions here for using type converters with your database. Based on the answer here and translating it, we get the following functions.

class Converters {
  @TypeConverter
  fun stringToBitmap(value: String?): Bitmap? {
    value ?: return null
    val bytes = Base64.decode(value, Base64.DEFAULT)
    val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    if (bitmap == null) {
        Log.e("stringToBitmap converter", "Failed to decode image.")
    }
    return bitmap
  }

  @TypeConverter
  fun bitmapToString(bitmap: Bitmap?): String? {
    bitmap ?: return null
    val stream = ByteArrayOutputStream()
    if (!bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream)) {
        Log.e("bitmapToString converter", "Failed to compress image.")
        return null
    }
    return Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT)
  }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Added this code but still getting same error. @Tenfour04 – Jorpy Jul 27 '23 at 21:08
  • Did you add the class to your database as show. In the linked instructions? – Tenfour04 Jul 27 '23 at 21:36
  • Yes added to database – Jorpy Jul 28 '23 at 06:43
  • The issue with the TypeConverter pair, is that they are converting to/from a Bitmap object. The **image** field (column) of the **`Item`** is not for a `Bitmap` but for a **`List>?`** i.e. the type of of **image** field rather than part of the type. Thus the TypeConverter pair expected should convert from/to a **`List>?`** not just a **`Bitmap`**. – MikeT Jul 30 '23 at 04:58