Home » Android » android – Room typeConverter(List<ByteArray>) doesn't work-Exceptionshub

android – Room typeConverter(List<ByteArray>) doesn't work-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

Error log is :

error: Cannot figure out how to save this field into database. You
can consider adding a type converter for it.
private final java.util.Listbyte[]> photo = null;

I did all of answer in stackoverflow but it still doesn’t work.

Memo.class

@Entity
data class Memo (
    @PrimaryKey(autoGenerate = true) val id: Int?,
    @ColumnInfo(name = "title") val title: String?,
    @ColumnInfo(name = "content") val content: String?,
    @ColumnInfo(name = "photo", typeAffinity = ColumnInfo.BLOB) val photo: List<ByteArray>?
)

MemoDatabase.class

@Database(entities = arrayOf(Memo::class), version = 1)
@TypeConverters(Converters::class)
abstract class MemoDatabase : RoomDatabase() {
    abstract fun memoDao(): MemoDao

    companion object {
        @Volatile
        private var INSTANCE: MemoDatabase? = null

        fun getDatabase(context: Context): MemoDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    MemoDatabase::class.java,
                    "memo_database"
                ).build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

Converters.class

class Converters {

        @TypeConverter
        fun fromString(value: String): List<ByteArray> {
            val type = object : TypeToken<List<ByteArray>>() {}.type
            return Gson().fromJson(value, type)
        }

        @TypeConverter
        fun fromList(list: List<ByteArray>): String {
            val type = object : TypeToken<List<ByteArray>>() {}.type
            return Gson().toJson(list, type)
        }
}
How to&Answers: