I have been having issue with hilt injection as I am relatively new to the concept of DI,
Here is the problem I have a class which manages my app session(Shared preference) and I want to inject that class to my use case(Activity/Fragment), now when I do this it throws this error
"lateinit property sessionManager has not been initialized"
code for SessionManager.kt
class SessionManager @Inject constructor(private val preferences: SharedPreferences) {
fun getTheme() = preferences.getInt(Constants.THEME_KEY, AppCompatDelegate.MODE_NIGHT_NO)
fun setTheme(value: Int) {
val editor = preferences.edit()
editor.putInt(Constants.THEME_KEY, value)
editor.apply()
}
}
code for appmoudle.kt
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideSharedPreferences(@ApplicationContext context: Context) =
context.getSharedPreferences(
Constants.PREF_NAME, Context.MODE_PRIVATE
)
@Singleton
@Provides
fun provideSessionManager(preferences: SharedPreferences) =
SessionManager(preferences)
}
code for the activity I am injecting it in
@AndroidEntryPoint
class TrendingRepoActivity : BaseActivity(), View.OnClickListener {
private lateinit var viewModel: TrendingRepoViewModel
private lateinit var binding: ActivityTrendingReposBinding
@Inject
lateinit var sessionManager: SessionManager
override fun onCreate(savedInstanceState: Bundle?) {
AppCompatDelegate.setDefaultNightMode(sessionManager.getTheme())
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_trending_repos)
setSupportActionBar(binding.appBarLayout.toolbar)
binding.errorView.retryBtn.setOnClickListener(this)
init()
}
}