我一直有手柄注射的问题,因为我对DI的概念相对较新,这是一个问题,我有一个管理我的应用程序会话(共享首选项(的类,我想将该类注入到我的用例(活动/片段(中,现在当我这样做时,它会抛出这个错误
"lateinit属性sessionManager尚未初始化";
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()
}
}
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)
}
我在中注入的活动代码
@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()
}
}
好吧,所以在挖掘出这个问题后,我做不是刀柄问题,而是一个小错误
问题出现在我在super.oncreate之前调用注入类的活动中
@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?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setDefaultNightMode(sessionManager.getTheme())
binding = DataBindingUtil.setContentView(this,
R.layout.activity_trending_repos)
setSupportActionBar(binding.appBarLayout.toolbar)
binding.errorView.retryBtn.setOnClickListener(this)
init()
}
}