1
votes

I try save custom type in room database. I always getting an error

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

I created converter for OutboxItemCache

My entity

@Entity(tableName = "request")
class RequestCache(
    @ColumnInfo(name = "requestId")
    @PrimaryKey var id: String = "",
    @TypeConverters(RequestConverter::class)
    var outboxItemCache: OutboxItemCache)

My RequestConverter

class RequestConverter {
companion object {
    private val gson = Gson()

    @TypeConverter
    fun stringToOutboxItem(string: String): OutboxItemCache? {
        if (TextUtils.isEmpty(string))
            return null
        return gson.fromJson(string, OutboxItemCache::class.java)
    }

    @TypeConverter
    private fun outboxItemToString(outboxItem: OutboxItemCache): String {
        return gson.toJson(outboxItem)
    }

}
}

This my class OutboxItemCache

class OutboxItemCache(
    var id: String = "",
    val numder: String,
    date: String,
    val headerDate: String,
    name: String,
    val certCount: String,
    val status: String,
    val statusColor: Int,
    var statusInfo: String? = null,
    val vetCertIds: List<String>
  )

The error never disappeared

1
Did you add @TypeConverters({RequestConverter.class}) to your AppDatabase class? - Tiago Ornelas

1 Answers

0
votes

As per google's documentation:

@Database(entities = {User.class}, version = 1)
@TypeConverters({RequestConverter.class})
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

You need to register your TypeConverters to your Database class.

EDIT:

In kotlin:

@Database(entities = arrayOf(User::class), version = 1)
@TypeConverters(RequestConverter::class)
abstract class AppDatabse : RoomDatabase() {
    abstract fun userDAO(): UserDAO    
}

The only line of code here that matters to you is

@TypeConverters(RequestConverter::class)

as you should already have the others.

EDIT 2:

Try writing your converter class as follows:

class RequestConverter {
@TypeConverter
fun stringToOutboxItem(string: String): OutboxItemCache? {
    if (TextUtils.isEmpty(string))
        return null
    return Gson().fromJson(string, OutboxItemCache::class.java)
}

@TypeConverter
private fun outboxItemToString(outboxItem: OutboxItemCache): String {
    return Gson().toJson(outboxItem)
}