Home > database >  @Inject for Hilt is giving UninitializedPropertyAccessException
@Inject for Hilt is giving UninitializedPropertyAccessException

Time:06-02

I am using Hilt in my project, and it is working fine everywhere apart from this one file.

abstract class SomeFile {
  
    @Inject
    lateinit var useCase: UseCase

    fun setData() {
       if (useCase.driver == 1){ do something }
       else { do something }
    }
}

This same "UseCase" inject is working in another files like viewmodel and activity. But only in this abstract class file is where I am getting this exception. What could be the issue here?

Module class

@Module
@InstallIn(SingletonComponent::class)
object HiltUseModule {
    @Provides
    @Singleton
    fun getUseCase(stateMachine: StateMachine): UseCase {
        return createProxyInstance(stateMachine)
    }
}

The app doesn't crash or anything. It just goes to the if condition and doesn't do anything. I used debug to check what is the value of 'useCase' there, and it shows the exception UninitializedPropertyAccessException.

Thanks in advance.

CodePudding user response:

Try this :

abstract class SomeFile {
 
    fun setData(useCase : UseCase) {
       if (useCase.driver == 1){ do something }
       else { do something }
    }
}

What it does is that the parameter that you pass in function will find object of UseCase from wherever it can.

CodePudding user response:

Rather than field injection, you should use constructor injection to acquire an instance of SomeFile.

class SomeFile @Inject internal constructor(private val useCase: UseCase) {
  fun setData() {
    if (useCase.driver == 1){ do something }
      else { do something }
    }
  }
}

Then, you will need to inject this into some component which is an entry point (whether that's your ViewModel, Fragment, or Activity:

@AndroidEntryPoint(AppCompatActivity::class)
class MyActivity : Hilt_AppCompatActivity() {
  @Inject internal lateinit var someFile: SomeFile

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    someFile.setData()
  }
}
  • Related