I download several files by URL
from the network using the okHttp3
library and in the body of the response, receiving a ByteArray
(like response.body?.bytes()
). Next, I need to save these files as a ByteArray
into the room library.
try {
val request = okhttp3.Request.Builder()
.url(url)
.build()
val response = httpClient.newCall(request).execute()
fileDao.add(
FileDatabaseEntity(
domain = url,
value = responce.body?.bytes() ?: ByteArray(0),
)
)
} catch (e: Exception) {
AppLogger.tag(TAG).e("Processing $url| Error: $e")
}
My database entity looks like:
@Entity(tableName = FILE)
class FileDatabaseEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ID)
val id: Long = 0,
@ColumnInfo(name = DOMAIN)
val domain: String,
@ColumnInfo(name = VALUE, typeAffinity = ColumnInfo.BLOB)
var value: ByteArray,
) {
companion object {
const val FILE = "file"
const val ID = "id"
const val DOMAIN = "domain"
const val VALUE = "value"
}
}
but in this case, when trying to add an object to the database with
@Insert
fun add(file: FileDatabaseEntity)
I get an error java.lang.IllegalStateException: closed
in catch
block for add
method.
At the same time, if I specifically specify the value only as ByteArray(0)
– it saves a record with an empty value for this field. It also works correctly if I specify a string with a random value as the field type (which indicates that the database as a whole is correctly configured – I can write, read, delete table records).
What is my mistake in saving the ByteArray to the Room table?