I trying to add a type converter for my entity, which presented below:
@Entity(tableName = "wall_items_table")
data class WallItemEntity(
@PrimaryKey(autoGenerate = true)
val databaseId: Int = 0,
val attachments: List<Attachment>,
val likes: Likes
)
in hilt module, which provides database:
@Module
@InstallIn(SingletonComponent::class)
internal object DatabaseModule {
@Singleton
@Provides
fun provideDatabase(
@ApplicationContext context: Context,
likesConverter: LikesConverter,
attachmentsConverter: AttachmentsConverter
): VkFriendsApplicationDatabase {
return Room.databaseBuilder(
context = context,
klass = VkFriendsApplicationDatabase::class.java,
name = "vkFriendsApplicationDatabase.db"
)
.addTypeConverter(likesConverter)
.addTypeConverter(attachmentsConverter)
.build()
}
}
But room still don’t see converters, and throws the error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
Here is my abstract class BaseConverter<T>
, which represents base logic for all converters:
abstract class BaseConverter<T> {
protected abstract val jsonAdapter: JsonAdapter<T>
@TypeConverter
fun toJson(data: T?): String {
return try {
data?.let { jsonAdapter.toJson(it) } ?: ""
} catch (e: IOException) {
""
}
}
@TypeConverter
fun fromJson(json: String): T? {
return try {
jsonAdapter.fromJson(json)
} catch (e: IOException) {
null
}
}
}
Implementations. I tried to remove abstract class and put functions annotated by TypeConverter
directly to these classes, but it whatever not works
@ProvidedTypeConverter
class LikesConverter @Inject constructor(
override val jsonAdapter: JsonAdapter<Likes>
) : BaseConverter<Likes>()
@ProvidedTypeConverter
class AttachmentsConverter @Inject constructor(
override val jsonAdapter: JsonAdapter<List<Attachment>>
) : BaseConverter<List<Attachment>>()
And database:
@Database(
entities = [
FriendEntity::class,
UserEntity::class,
WallItemEntity::class
],
version = 1
)
internal abstract class VkFriendsApplicationDatabase : RoomDatabase() {
abstract val friendsDao: FriendsDao
abstract val usersDao: UsersDao
}