Внедрение ViewModel с помощью DaggerHilt не компилируется

Я прочитал документацию об использовании Dagger Hilt для внедрения ViewModels. Я пытался реализовать в своем приложении, но при сборке Gradle постоянно получаю сообщение об ошибке, и проект не компилируется. Как я могу исправить эту проблему?

/home/amcap1712/Documents/MusicBrainzAndroid/app/src/main/java/org/metabrainz/mobile/presentation/features/artist/ArtistViewModel.java:19: error: [Hilt]
public class ArtistViewModel extends LookupViewModel {
       ^
  org.metabrainz.mobile.presentation.features.artist.ArtistViewModel, expected to be annotated with @DefineComponent. Found: 
  [Hilt] Processing did not complete. See error above for details.warning: File for type 'org.metabrainz.mobile.App_HiltComponents' created in the last round will not be subject to annotation processing.

Вот соответствующие файлы,
build.gradle

....
dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0-beta02'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
}
....

app / build.gradle

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

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "org.metabrainz.android"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 33

        versionName "3.1"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildFeatures {
        viewBinding = true
        dataBinding = true
    }

    buildTypes {
        release {
            minifyEnabled false
            // proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions{
        disable 'InvalidPackage'
        disable 'MissingTranslation'
    }
    compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

    ndkVersion '21.2.6472646'
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.0-alpha01'
    implementation "androidx.navigation:navigation-fragment:$navigationVersion"
    implementation "androidx.navigation:navigation-ui:$navigationVersion"
    implementation 'androidx.lifecycle:lifecycle-runtime:2.3.0-alpha05'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-alpha05'
    implementation 'androidx.lifecycle:lifecycle-viewmodel:2.3.0-alpha05'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-common-java8:2.3.0-alpha05'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation "androidx.activity:activity:1.1.0"
    implementation "androidx.fragment:fragment-ktx:1.2.5"

    //webservice Setup
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.retrofit2:retrofit:2.7.1'
    implementation 'com.squareup.okhttp3:okhttp:4.3.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.3.1'

    //Image downloading and Caching library
    implementation 'com.squareup.picasso:picasso:2.71828'

    //Kotlin setup
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

    //Fragment Setup For Kotlin
    implementation 'androidx.navigation:navigation-fragment-ktx:2.0.0-rc02'
    implementation 'androidx.navigation:navigation-ui-ktx:2.0.0-rc02'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'

    //Test Setup
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Tagger & Metadata Setup
    implementation 'com.github.QuickLyric:fpcalc-android:1.0.1'
    implementation 'org.bitbucket.ijabz:jaudiotagger:android-SNAPSHOT'
    implementation 'info.debatty:java-string-similarity:1.2.1'

    //Design Setup
    implementation 'androidx.browser:browser:1.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.0-alpha04'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta8'
    implementation "com.google.android.material:material:$supportlibVersion"
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.17'
    implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    implementation 'androidx.preference:preference:1.1.1'
    implementation 'me.dm7.barcodescanner:zbar:1.9.13'
    implementation "com.airbnb.android:lottie:$lottieVersion"

    implementation "androidx.paging:paging-runtime:3.0.0-alpha02"

    implementation "com.google.dagger:hilt-android:2.28-alpha"
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
    implementation "com.google.dagger:dagger:2.28"
    annotationProcessor "com.google.dagger:dagger-compiler:2.28"
    annotationProcessor "com.google.dagger:hilt-android-compiler:2.28-alpha"
    annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
    kapt "com.google.dagger:dagger-compiler:2.28"
    kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
    kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
}

ArtistViewModel.java Этот класс расширяет другой абстрактный класс LookupViewModel, который я создал, с помощью некоторых общих функций, которые я использую во многих моделях просмотра.

....
public class ArtistViewModel extends LookupViewModel {
    ....
    @ViewModelInject
    public ArtistViewModel(LookupRepository repository) {
        super(repository);
        .....
    }
....

LookupRepositor.java

....
@Module
@InstallIn(ArtistViewModel.class)
public class LookupRepository {
    private static LookupRepository repository;
    
    private LookupRepository() {
    }

    @Singleton
    @Provides
    public static LookupRepository getRepository() {
        if (repository == null) repository = new LookupRepository();
        return repository;
    }
....

person Kartik Ohri    schedule 16.07.2020    source источник


Ответы (3)


@Module
@InstallIn(SingletonComponent.class)
public class LookupRepository {

    @Singleton
    @Provides
    public static LookupRepository getRepository() {
        return new LookupRepository();
    }
}

Ваша проблема в InstallIn. Используйте SingletonComponent для области применения или ActivityRetainedComponent для области просмотра модели

См. Эту ссылку для получения дополнительной информации.

person Saeed Lotfi    schedule 16.07.2020
comment
Моя проблема заключалась в том, что я использовал модель просмотра во фрагменте, а на фрагменте я не упоминал @AndroidEntryPoint. Я упоминал об этом в Activity, но не в Fragment. - person Sharad; 06.08.2020

// @Module
// @InstallIn(ArtistViewModel.class)
// public class LookupRepository {
    // private static LookupRepository repository;
    
    // private LookupRepository() {
    // }

    // @Singleton
    // @Provides
    // public static LookupRepository getRepository() {
        // if (repository == null) repository = new LookupRepository();
        // return repository;
    // }

Вы можете полностью удалить этот модуль с помощью следующего кода:

@Singleton
public class LookupRepository {
    @Inject
    LookupRepository() {}
}

И теперь он доступен из ApplicationComponent (скоро будет называться SingletonComponent).

person EpicPandaForce    schedule 21.07.2020

Напишите @AndroidEntryPoint во всех фрагментах и ​​в Activity и обновите зависимости.

person Bhavya Varmora    schedule 17.10.2020