Does anyone know a way to add a type converter to room database using dagger2. My application throws an error that the type converter is missing from the database configuration. Here is my code:
DatabaseModule
@Module
object DatabaseModule {
@Singleton
@Provides
fun provideDatabase(applicationContext: MobileApplication): LocalRoomDatabase =
Room.databaseBuilder(applicationContext, LocalRoomDatabase::class.java, "local_database")
.addTypeConverter(DateTimeConverter::class)
.fallbackToDestructiveMigration()
.build()
@Singleton
@Provides
fun provideRoomDao(database: LocalRoomDatabase) = database.roomDao()
}
LocalRoomDatabase
@Database(entities = arrayOf(IND1::class, STT4::class, UNT1::class, USR1::class, WHS1::class), version = 2)
@TypeConverters(DateTimeConverter::class )
abstract class LocalRoomDatabase : RoomDatabase() {
abstract fun roomDao(): RoomDao
}
DateTimeConverter
@ProvidedTypeConverter
class DateTimeConverter {
@TypeConverter
fun toDate(dateString: String): LocalDateTime? {
return if (dateString == null) {
null
} else {
LocalDateTime.parse(dateString)
}
}
@TypeConverter
fun toDateString(date: LocalDateTime): String? {
return if (date == null) null else date.toString()
}
}
How to correctly inject a type converter using dagger2?
When adding your type converter with addTypeConverter
, you're required to provide an instance of your converter, not the class reference. So you should be doing something like this:
addTypeConverter(DateTimeConverter())
However here it doesn't look like you need to inject your type converter in the first place, if it's not necessary you can just get rid of the ProvidedTypeConverter
annotation and the addTypeConverter
call.