Activity has no zero argument constructor - Dagger Hilt

2.4k views Asked by At

I am using Dagger Hilt for dependecy Injection

I have a class -

SessionManager

class SessionManager (context: Context){

private val dataStore: DataStore<Preferences> = context.createDataStore(
    name = "session"
)

companion object{
    val IS_LOGIN = preferencesKey<Boolean>(name = "is_login")
}

suspend fun setLogin(isLogin: Boolean){
    dataStore.edit {
            preferences ->
        preferences[IS_LOGIN] = isLogin
    }
 }
}

I am trying to call the setLogin func in an activity like this -

MainActivity

@AndroidEntryPoint
 class MainActivity @Inject constructor(private val sessionManager: SessionManager) : 
 AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {

  lifecycleScope.launch {
        sessionManager.setLogin(true)
    }
}

MyApplication

@HiltAndroidApp
class MyApplication : Application() {
 }

Manifest

<application
    android:name=".MyApplication"
    android:allowBackup="true"/>

As you can see, I have used the @AndroidEntryPoint Annotation but I still get this runtime error

*java.lang.Class<com.app.app.activities.MainActivity> has no zero argument constructor*
1

There are 1 answers

0
Nongthonbam Tonthoi On

For MainActivity I think you cannot do contructor injection, so try field injection as:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject
    lateinit var sessionManager: SessionManager
    
    override fun onCreate(savedInstanceState: Bundle?) {    
        lifecycleScope.launch {
            sessionManager.setLogin(true)
        }
    }
}

Now you should be able to use sessionManager inside onCreate