简体   繁体   中英

Android: Kotlin with Dagger

I'm new on Dagger. I want to use Dependecy Injection system on my project with Dagger 2 . When I was debug my project injected fields is showing null .

What's wrong?

class App : Application() {

    lateinit var component: AppComponent

    @Inject lateinit var database: AppDatabase //--> null??
    @Inject lateinit var      app: App //--> null??

    override fun onCreate() {
        super.onCreate()

        component = DaggerAppComponent.builder()
                .appModule(AppModule(this))
                .databaseModule(DatabaseModule())
                .build().apply {
            inject(this@App)
            Timber.d("App: $app")
        }
    }

}

@AppScope
@Component(modules = arrayOf(AppModule::class, DatabaseModule::class))
interface AppComponent {

    fun inject(application: Application)

}

@Module
class AppModule(private val application: Application) {

    @Provides
    @AppScope
    fun provideApplication() = application

    @Provides
    @AppScope
    @ApplicationContext
    fun provideContext() = application.applicationContext!!

}

@Module(includes = arrayOf(AppModule::class))
class DatabaseModule {

    @Inject
    lateinit var context: Context

    private val database by lazy {
        Room.databaseBuilder(context, AppDatabase::class.java, AppDatabase.CONS.NAME)
                .build()
    }

    @Provides
    @AppScope
    fun provideDatabase(context: Context): AppDatabase = database

}

Gradle:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 26

        applicationId "com.kibar.app"
        versionCode 1100
        versionName '1.1.0'
        archivesBaseName = "app-$versionName-$versionCode"
        multiDexEnabled true

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath = true
            }
        }
    }

    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }

        debug {
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    packagingOptions {
        exclude 'META-INF/rxjava.properties'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

kapt {
    generateStubs = true
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:multidex:1.0.2'
    implementation "com.android.support:design:$android_support_version"
    implementation "com.android.support:appcompat-v7:$android_support_version"
    implementation "com.android.support:recyclerview-v7:$android_support_version"
    implementation "com.android.support:cardview-v7:$android_support_version"
    implementation "com.google.firebase:firebase-ads:$firebase_version"
    implementation "com.google.firebase:firebase-crash:$firebase_version"
    implementation "com.google.firebase:firebase-config:$firebase_version"
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.jakewharton.timber:timber:4.5.1'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"

    implementation "com.google.dagger:dagger:$dagger_version"
    implementation "com.google.dagger:dagger-android:$dagger_version"
    implementation "com.google.dagger:dagger-android-support:$dagger_version"
    kapt "android.arch.persistence.room:compiler:$room_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
    provided 'org.glassfish:javax.annotation:10.0-b28'
}

apply plugin: 'com.google.gms.google-services'

Top gradle:

buildscript {
    ext{
        android_support_version = "26.1.0"
        kotlin_version          = "1.1.51"
        firebase_version        = "11.4.2"
        room_version            = "1.0.0-alpha9-1"
        dagger_version          = "2.11"
    }

    repositories {
        jcenter()
        maven { url "https://maven.google.com" }
        maven { url "https://jitpack.io" }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-rc2'
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }
        maven { url "https://jitpack.io" }
    }

    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xmaxerrs" << "1000"
        }
    }
}
fun inject(application: Application)

Should be

fun inject(application: App)

Don't forget to specify the App class as the application:name in the AndroidManifest.xml

<application
    android:name=".application.App"

And you must make sure you define the compiler with kapt scope

kapt 'com.google.dagger:dagger-compiler:2.x'

and you also apply kotlin-kapt plugin

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

And if you use field injection, you need to specify the annotation target (in Kotlin):

@field:Inject lateinit var thing: Thing;

You were also missing a qualifier for @ApplicationContext on your provider method argument, so that was added as well.

fun database(@ApplicationContext context: Context) : Database {
  ...

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