简体   繁体   English

安卓:科特林与匕首

[英]Android: Kotlin with Dagger

I'm new on Dagger. 我是Dagger的新手。 I want to use Dependecy Injection system on my project with Dagger 2 . 我想在Dagger 2项目上使用Dependecy Injection系统。 When I was debug my project injected fields is showing null . 当我调试时,项目注入的字段显示为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 不要忘记在AndroidManifest.xml中将App类指定为application:name

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

And you must make sure you define the compiler with kapt scope 并且必须确保使用kapt范围定义编译器

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

and you also apply kotlin-kapt plugin 而且您还应用了kotlin-kapt插件

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): 而且,如果您使用字段注入,则需要指定注释目标(在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. 您还缺少提供程序方法参数上@ApplicationContext的限定符,因此也添加了该限定符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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