8

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?

LordCommanDev
  • 922
  • 12
  • 38
  • Why don't you just pass the context and let your implementation select preferences file and mode internally? Can you post full error message? – mlc Apr 16 '20 at 21:53

2 Answers2

14

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

Oscar Sequeiros
  • 164
  • 1
  • 3
4

I dont know, why koin is not able to suggest org.koin.android.ext.android.inject path when using by inject() but I fixed this issue with below code snippet:

private val foo: FooClass by KoinJavaComponent.inject(FooClass::class.java)
Abhishek Dutt
  • 1,308
  • 7
  • 14
  • 24