Ankit
Bobble Engineering
Published in
2 min readOct 27, 2022

--

“Cannot figure out how to save this field into database” exception in Room Database Kotlin

Build Error

Sometimes, you need your app to store a custom data type e.g. Bitmap in a single database column. You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.

So consider a case where we try to store bitmap in our Room Database it will throw an build error “Cannot figure out how to save this field into database. You can consider adding a type converter for it. — picture in com.example.cameragallery.DatabaseData” this is because our database don’t know how to store data which is of Bitmap datatype.So here TypeConverters come into picture to solve this problem. What we have to do is to just add a Converter.kt class which includes functions to convert custom datatypes into Room preffered datatype, like in our case we need to convert bitmap to byteArray and byteArray to bitmap and then annotate it to our database class so that when database try to store bitmap it automatically use that function and do conversions.

class Converter {

@TypeConverter
fun fromBitmap(bitmap: Bitmap) : ByteArray {
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream)
return outputStream.toByteArray()
}
@TypeConverter
fun toBitmap(byteArray: ByteArray) : Bitmap {
return BitmapFactory.decodeByteArray(byteArray,0,byteArray.size)
}
}
Notes:
ByteArrayOutputStream():This class implements an output stream in which the data is written into a byte array.

Now just inform our database class that listen if you get a bitmap use my converter class to convert data into preffered datatypes .So in order to do this we use the below code

import ...//just add this below Line in your database class and its done
@TypeConverters(Converter::class)

@Database(entities = [DatabaseData::class],version = 1, exportSchema = false)
abstract class OurDatabase: RoomDatabase() {
// database creation body
}

This will solve the above mentioned Build error but the way of storing bitmap in database is not preferred because it will work good for low resolution picture but if you try to store high resolution picture the app will surely crash giving an “Blob Too Big” exception.How to fix it ?

Go checkout 👉 https://github.com/prasadankitt/ImageApp

--

--