简体   繁体   中英

Dagger hilt injecting into activity results in UninitializedPropertyAccessException error

I am trying to inject a class into an activity using dagger hilt using a Module. I've looked through tutorials and countless SO posts. I cannot tell what I'm doing wrong.

I have a DataStoreManger class that i'm trying to use in an activity.

class DataStoreManager (@ApplicationContext appContext: Context) {...}

I have an AppModule that provides a DataStoreManager.

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
   @Provides
   @Singleton
   fun provideDataStoreManager(@ApplicationContext appContext: Context): 
      DataStoreManager = DataStoreManager(appContext)
}

Then I'm trying to use DataStoreManager in MainActivity.

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
   @Inject lateinit var dataStoreManager: DataStoreManager

   private val userPreferencesFlow = dataStoreManager.userPreferencesFlow
}

This results in an uninitialized property access exception

     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property 
     dataStoreManager has not been initialized

When you use

@Inject lateinit var dataStoreManager

The dataStoreManager is only actually injected during the call to super.onCreate() .

However, when you create a property such as

private val userPreferencesFlow = dataStoreManager.userPreferencesFlow

This property is created immediately as part of the construction of your MainActivity class - it doesn't wait until onCreate() runs, hence the error you are receiving.

Generally, the easiest way to avoid this is by only access the userPreferencesFlow from your injected manager when you actually want to collect it, which is presumably after super.onCreate() .

However, if you want to still create your flow as a member variable at the activity level, you can use by lazy :

private val userPreferencesFlow by lazy {
    dataStoreManager.userPreferencesFlow
}

The lazy block will only be executed lazily - eg, the first time you actually use the member variable, thus ensuring that your @Inject variable has actually been injected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM