Issue
I'm trying to implement Koin in my project. So far, I did this:
My shared preferences class:
class MPCUtilSharedPreference(private val sharedPreferences: SharedPreferences{}
I want to inject that class in other classes. So, I create my MainApplication class:
class MPCMainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MPCMainApplication)
modules(modules)
}
}
}
This is my module class:
private val appModule = module {
single {
MPCUtilSharedPreference(
androidContext().getSharedPreferences(
BuildConfig.APP_PREFERENCE,
Context.MODE_PRIVATE
)
)
}
}
val modules = listOf(appModule)
And the I'm trying to inject it:
class MPCNetworkInterceptor : Interceptor {
private val utilSharedPreferences: MPCUtilSharedPreference by inject() }
The error says:
No value passed for parameter 'clazz'
I'm trying to use
import org.koin.android.ext.koin.androidContext
But the AS uses
import org.koin.java.KoinJavaComponent.inject
This is my gradle:
implementation 'org.koin:koin-android:2.1.5'
implementation 'org.koin:koin-androidx-scope:2.1.5'
implementation 'org.koin:koin-androidx-viewmodel:2.1.5'
implementation 'org.koin:koin-androidx-fragment:2.1.5'
Any idea about what's the problem here?
Solution
You're trying to use by inject()
delegate from an place that is neither an Activity nor Fragment, that's why the IDE is importing :
import org.koin.java.KoinJavaComponent.inject
If you want to use MPCUtilSharedPreference
from MPCNetworkInterceptor
, you can pass it as parameter in MPCNetworkInterceptor
constructor. And obviously, add this in your module.
Otherwise, you could implement KoinComponent
Answered By - Oscar Sequeiros
Answer Checked By - Mildred Charles (JavaFixing Admin)