我是依赖注入的新手,目前正在使用 dagger-hilt。我必须使用类型转换器才能在实体中插入列表。
在运行时,我面临崩溃,因为尽管我添加了转换器,但数据库配置中缺少转换器。
下面是我关于类型转换器、数据库类和应用程序模块的代码
@ProvidedTypeConverter
class BundleConverter {
@TypeConverter
fun fromPackageBundleList(countryLang: List<PackageBundle?>?): String? {
if (countryLang == null) {
return null
}
val gson = Gson()
val type: Type = object : TypeToken<List<PackageBundle?>?>() {}.type
return gson.toJson(countryLang, type)
}
@TypeConverter
fun toPackageBundleList(countryLangString: String?): List<PackageBundle>? {
if (countryLangString == null) {
return null
}
val gson = Gson()
val type: Type = object : TypeToken<List<PackageBundle?>?>() {}.type
return gson.fromJson<List<PackageBundle>>(countryLangString, type)
}
}
@Database(
entities = [Service::class,SoundEffect::class],
version = 3,
exportSchema = false
)
@TypeConverters(BundleConverter::class)
abstract class UserDatabase : RoomDatabase() {
abstract fun getYourDao(): UserDao
}
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Singleton
@Provides
fun provideYourDatabase(
@ApplicationContext app: Context
) = Room.databaseBuilder(
app,
UserDatabase::class.java,
"your_db_name"
)
.addTypeConverter(BundleConverter::class)
.build()
@Singleton
@Provides
fun provideYourDao(db: UserDatabase) = db.getYourDao()
}
答案 0 :(得分:0)
尝试从您的数据库转换器类中删除可选值处理:
class BundleConverter {
@TypeConverter
fun fromPackageBundleList(countryLang: List<PackageBundle>): String =
return Gson().toJson(countryLang)
@TypeConverter
fun toPackageBundleList(countryLangString: String): List<PackageBundle> {
val type: Type = object : TypeToken<List<PackageBundle>>() {}.type
return Gson().fromJson(countryLangString, type)
}
}