2017-07-14 64 views
1

我剛剛熟悉新房間庫,並且我遇到了一個煩人的問題。我有一個UserRepository類,它根據多個因素從網絡和本地存儲裝載數據。當我想從數據庫中注入DAO對象,我得到這個錯誤:Kotlin中的匕首房間:當注入類時Dao爲空

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull

這裏是代碼的部分,什麼可能導致此錯誤

ApplicationModule

@Module 
class ApplicationModule(val application: CustomApplication) { 
    private val BASE_URL = "https://api.stackexchange.com/2.2/" 

    @Provides 
    @Singleton 
    fun provideAppContext() : Context = application 

    @Provides 
    @Singleton 
    fun provideRetrofit(): Retrofit = Retrofit.Builder() 
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 
      .addConverterFactory(GsonConverterFactory.create(Gson())) 
      .baseUrl(BASE_URL) 
      .build() 

    @Provides 
    @Singleton 
    fun provideUserRepository(retrofit: Retrofit, database: AppDatabase) = 
      UserRepository(
        retrofit.create(UserService::class.java), 
        retrofit.create(QuestionService::class.java), 
        database.userDao()) 

    @Provides 
    @Singleton 
    fun provideDatabase(context: Context) 
      = Room.databaseBuilder(context, AppDatabase::class.java, "db-name").build() 
} 

userDAO的

@Dao 
interface UserDao { 
    @Query("SELECT * FROM user") 
    fun getAllUsers() : Flowable<List<User>> 

    @Insert 
    fun insertAll(users: List<User>) 
} 

AppDatabase

@Database(entities = arrayOf(User::class), version = 1) 
abstract class AppDatabase : RoomDatabase() { 
    abstract fun userDao() : UserDao 
} 

有誰知道爲什麼database.userDao()可能爲空?在我從數據庫請求它之前,是否需要執行額外的初始化?我無法找到信息關於這個隨時隨地

回答

0

我使用這個代碼:

@Database(entities = arrayOf(User::class), version = 1) 
abstract class AppDatabase : RoomDatabase() { 

    abstract fun userModel(): UserDao 

    companion object { 
     private const val DB_NAME = "users.db" 

     fun createPersistentDatabase(context: Context): AppDatabase 
       = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, DB_NAME).build() 
    } 
} 

,我使用它注射:

@Singleton @Provides fun provideApp(context: Context) = AppDatabase.createPersistentDatabase(context) 
+0

這基本上是相同的代碼,只需創建代碼被移動到AppDatabase類 –