简体   繁体   中英

How to inject SP via Dagger 2.11 with Kotlin?

I'm using Dagger 2 with Kotlin. All works fine, but when I'm trying to Inject SharedPreferences to Activity my project doen't even creating. Gradle Console says:

di\\AppComponent.java:6: error: [dagger.android.AndroidInjector.inject(T)] android.content.SharedPreferences is not nullable, but is being provided by @org.jetbrains.annotations.Nullable @android.support.annotation.Nullable @Singleton @Provides android.content.SharedPreferences myapp.di.Modules.SharedPrefModule.providePreferences(android.content.Context) e:

e: public abstract interface AppComponent { e: ^ e:
at: android.content.SharedPreferences is injected at e:
myapp.mvp.StartScreen.StartActivity.sharedPref e:
myapp.mvp.StartScreen.StartActivity is injected at e:
dagger.android.AndroidInjector.inject(arg0) e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing

SharedPreferencesModule:

    @Module
class SharedPrefModule{

    @Provides
    @Singleton
     fun providePreferences (context : Context): SharedPreferences? {
        return context.getSharedPreferences(SHARED_PREFERENCES_SETTINGS, Context.MODE_PRIVATE)
    }
}

AppComponent:

    @Singleton
@Component(modules=arrayOf(AppModule::class, AndroidSupportInjectionModule::class,
        SharedPrefModule::class, ActivityBuilder::class))
interface AppComponent {

    fun inject (app:App)

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(context: Application): Builder

        fun build(): AppComponent
    }
}

App:

class App : Application(),HasActivityInjector {
    @Inject
    lateinit var activityInjector : DispatchingAndroidInjector<Activity>

    override fun onCreate() {
        super.onCreate()
        DaggerAppComponent.builder().build().inject(this)

    }

    override fun activityInjector(): AndroidInjector<Activity> = activityInjector
}

Activity:

class StartActivity: AppCompatActivity(), HasActivityInjector {

    @Inject
    lateinit var activityInjector : DispatchingAndroidInjector<Activity>

    @Inject
    lateinit var sharedPref : SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.start_activity_layout)

//        var data = sharedPref.getString(SHARED_PREFERENCES_SETTINGS, "")
//        Log.d("tag", "data - $data")
    }

    override fun activityInjector(): AndroidInjector<Activity> = activityInjector
}

SharedPrefModule使用上下文来创建SharedPreferences实例,并且由于您不包括提供上下文的任何模块,因此Dagger可能无法创建SharedPreferences实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM