使用Room + LiveData + Dagger2 + Kotlin
db code:
@Database(entities = arrayOf(MonthlyBudget::class, Purchase::class), version = 1, exportSchema = false)
@TypeConverters(DateTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun budgetDAO(): BudgetDAO
abstract fun purchaseDAO(): PurchaseDAO
}
dagger2中提供db
的方法@Provides
fun providesAppDatabase(context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "my-budget-db").allowMainThreadQueries().build()
dagger 2中返回null的方法
@Provides
@Singleton
@Named("CurrentMonthBudget")
fun provideCurrentMonthBudget(repository: AppRepository): MonthlyBudget = repository.currentMonthBudget()
对象的注入
@Inject
@Nullable
@field:Named("CurrentMonthBudget")
lateinit var currentMonthBudget: MonthlyBudget
由于我得到了这个空数据
java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method
我是这样做的:创建了一个nullcheck,如果'If'返回'true',我在db中添加默认值。
@Database(entities = arrayOf(MonthlyBudget::class, Purchase::class), version = 1, exportSchema = false)
@TypeConverters(DateTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun budgetDAO(): BudgetDAO
abstract fun purchaseDAO(): PurchaseDAO
companion object {
fun getInstance(context:Context):AppDatabase {
val database = Room.databaseBuilder(context, AppDatabase::class.java, "my-budget-db").allowMainThreadQueries().build()
if (database.budgetDAO().queryCurrentMonthBudget() == null) {
database.budgetDAO().insert(MonthlyBudget(0), MonthlyBudget(0))
database.purchaseDAO().insert(Purchase("default",0))
}
return database
}
}
}
我该怎么办?填充数据库?如果是这样,告诉我更好的方法,还是有另一种方式?
答案 0 :(得分:1)
我认为您需要在@Nullable
上设置provideCurrentMonthBudget
。此外,因为这是kotlin,返回类型应该是MonthlyBudget?
- kotlin表示可以为?
的可空类型。