我是一个依赖注入的新手,目前正在使用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()
}发布于 2021-04-27 23:59:08
尝试从数据库转换器类中删除可选值处理:
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)
}
}https://stackoverflow.com/questions/67283179
复制相似问题