Home > Enterprise >  Injecting a repository with lateinit is leading to crash
Injecting a repository with lateinit is leading to crash

Time:03-18

I have injected my repository in an Activity with lateinit declaration. However, when I am calling the method of repository it is resulting in a crash saying lateinit property clearDbRepository has not been initialized.

class StartActivity : BaseActivity() {

    private lateinit var binding: StartEmptyPageBinding

    @Inject
    lateinit var clearDbRepository: ClearDbRepository

    override fun setupViews() {
        lifecycleScope.launch {
            clearDbRepository.clearLocalDatabase()
        }
    } 
}

My ClearDbRepository is:

@Singleton
class ClearDbRepository @Inject constructor(
    private val mainDatabase: LocalDB
) {
    suspend fun clearLocalDatabase() = withContext(Dispatchers.IO) { 
        mainDatabase.clearAllTables() 
    }
}

CodePudding user response:

If you are using the Hilt library, then most probably, according to your code snippet, you're missing an annotation. You must add the appropriate annotation above your Activity class, like this:

@AndroidEntryPoint
class StartActivity : BaseActivity() { }
  • Related