Error cannot find symbol dagger

Recent after update Android Studio (2.0.7) (maybe this is the cause) sometimes when building i get that error. Idea is that usually compilation goes well but sometimes I get dagger error. Is poss...

Recent after update Android Studio (2.0.7) (maybe this is the cause) sometimes when building i get that error.

Idea is that usually compilation goes well but sometimes I get dagger error.

Is possible that is problem in Dagger configuration?

Error itself:


Executing tasks: [:app:assembleDebug]

Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2311Library UP-TO-DATE
:app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:app:prepareComDaimajiaSwipelayoutLibrary120Library UP-TO-DATE
:app:prepareComF2prateekRxPreferencesRxPreferences101Library UP-TO-DATE
:app:prepareComGithubAakiraExpandableLayout141Library UP-TO-DATE
:app:prepareComGithubAfollestadMaterialDialogsCore0842Library UP-TO-DATE
:app:prepareComGithubCastorflexSmoothprogressbarLibraryCircular120Library UP-TO-DATE
:app:prepareComJakewhartonRxbindingRxbinding030Library UP-TO-DATE
:app:prepareComPnikosisMaterialishProgress17Library UP-TO-DATE
:app:prepareComTrelloRxlifecycle040Library UP-TO-DATE
:app:prepareComTrelloRxlifecycleComponents040Library UP-TO-DATE
:app:prepareComWdullaerMaterialdatetimepicker211Library UP-TO-DATE
:app:prepareIoReactivexRxandroid110Library UP-TO-DATE
:app:prepareMeRelexCircleindicator116Library UP-TO-DATE
:app:prepareMeZhanghaiAndroidMaterialprogressbarLibrary114Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:compileDebugJavaWithJavac
/home/ungvas/AndroidDev/Projects/FW/paynet-android/app/src/main/java/md/fusionworks/paynet/ui/activity/BaseActivity.java:23: error: cannot find symbol
import md.fusionworks.paynet.di.component.DaggerActivityComponent;
^
symbol: class DaggerActivityComponent
location: package md.fusionworks.paynet.di.component
/home/ungvas/AndroidDev/Projects/FW/paynet-android/app/src/main/java/md/fusionworks/paynet/PaynetApplication.java:7: error: cannot find symbol
import md.fusionworks.paynet.di.component.DaggerApplicationComponent;
^
symbol: class DaggerApplicationComponent
location: package md.fusionworks.paynet.di.component
2 errors

Incremental compilation of 66 classes completed in 3.719 secs.
:app:compileDebugJavaWithJavac FAILED
:app:compileRetrolambdaDebug

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:compileDebugJavaWithJavac'.

    Compilation failed; see the compiler error output for details.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 19.556 secs

Thanks.

Philip Kirkbride's user avatar

asked Jan 25, 2016 at 10:14

user1542447's user avatar

9

It’s seems that it have something to do with incremental compilation added in Gradle 2.10

I managed to fix it adding the following command to gradle:

-Pandroid.incrementalJavaCompile=false

You can add it in Android Studio in: File | Settings | Build, Execution, Deployment | Compiler adding it as a Command line option.

edit as of 2.0.0-beta3 the plugin gives a warning telling you that this option has been added to the Gradle DSL:

android {
    compileOptions.incremental = false
}

answered Jan 28, 2016 at 11:37

DanielDiSu's user avatar

DanielDiSuDanielDiSu

1,1391 gold badge11 silver badges10 bronze badges

3

I was using a pure Java Library module, but was using the kotlin plugin and the dagger dependencies, like this:

build.gradle

apply plugin: 'kotlin'
dependencies {
    implementation "com.google.dagger:dagger:2.22.1"
    kapt "com.google.dagger:dagger-compiler:2.22.1"
}

The error was, I missed to add the kotlin-kapt plugin. So, my build.gradle file ended up like this:

apply plugin: 'kotlin'
apply plugin: "kotlin-kapt" // make sure you added this line

dependencies {
    implementation "com.google.dagger:dagger:2.22.1"
    kapt "com.google.dagger:dagger-compiler:2.22.1"
}

answered Apr 10, 2019 at 16:16

Jorge E. Hernández's user avatar

1

You need to update your version 2.11 for dagger.

Your build.gradle‘s dependencies block should looks like following.

dependencies {
    // Other dependencies should go here
    compile "com.google.dagger:dagger:2.11"
    annotationProcessor "com.google.dagger:dagger-compiler:2.11"
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'javax.inject:javax.inject:1'
}

Hope this helps.

answered Sep 27, 2017 at 8:41

Hiren Patel's user avatar

Hiren PatelHiren Patel

51.6k21 gold badges171 silver badges150 bronze badges

2

Changes in 2017:

Android Studio Canary uses a newer version of Gradle and apt plugins may not work, replaced by annotationProcessor. It may fail despite the compiler warning saying that it will be removed in a future version of gradle.

Change this dependency line:

apt 'com.google.dagger:dagger-compiler:2.7'

to

annotationProcessor 'com.google.dagger:dagger-compiler:2.7'

and remove the apt plugin.

answered Aug 31, 2017 at 4:25

Kabliz's user avatar

KablizKabliz

3104 silver badges12 bronze badges

The latest version of Dagger (2.8) is causing this error. Make sure your dependencies are as mentioned below

apt 'com.google.dagger:dagger-compiler:2.7'
compile 'com.google.dagger:dagger:2.7'

answered Jan 28, 2017 at 12:46

fardown's user avatar

fardownfardown

6832 gold badges11 silver badges22 bronze badges

1

use the same dagger version for all the dagger dependencies. worked for me.

implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVersion"
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"


//define version in main build.gradle
ext {
    daggerVersion = '2.11'
}

answered Jan 30, 2019 at 9:58

rajeswari ratala's user avatar

2

I had a similar problem but for different reason.
I had the problem only when trying to generate the apk. Otherwise it was working correctly.
In my case the problem was that the class was in the test directory instead of the main directory for some unknown reason, I moved it to main and it worked.
Hope it helps someone

answered Feb 22, 2017 at 8:28

PhpLou's user avatar

PhpLouPhpLou

4303 silver badges16 bronze badges

1

File->InvalidateCaches/Restart worked for me

answered Nov 29, 2017 at 15:35

Jenison Gracious's user avatar

1

Make sure you are using Java version 1.7. Also, if something else is broken in your dagger pipeline, it will cause this error as well.

answered Nov 13, 2016 at 22:40

Horatio's user avatar

HoratioHoratio

1,6051 gold badge17 silver badges26 bronze badges

In my case none of above works.

Follow steps to generate DaggerApplicationComponent class.

  1. Clean project
  2. Rebuild project
  3. Import manually by Option + Return OR Alter + Enter if you do not have Auto import on fly setting in Android studio

Done

answered Sep 26, 2017 at 11:53

Hiren Patel's user avatar

Hiren PatelHiren Patel

51.6k21 gold badges171 silver badges150 bronze badges

0

You probably trying to Inject a class that is not Provided.
A common scenario is when you Provide an Interface and trying to inject the concrete class.

For example:

@Provides
@Singleton
IConnection getIConnection(){ return new Connection(); }

And trying to Inject it as follows:

@Inject
Connection mConnection;

answered Sep 7, 2020 at 7:40

Gal Rom's user avatar

Gal RomGal Rom

6,1192 gold badges40 silver badges33 bronze badges

If you have multimodule android application, then it is important that each .gradle file has kapt dependencies:

kapt "com.google.dagger:dagger-compiler:${dagger_version}"
kapt "com.google.dagger:dagger-android-processor:${dagger_version}"

answered Dec 28, 2021 at 12:31

Mladen Rakonjac's user avatar

Mladen RakonjacMladen Rakonjac

9,3827 gold badges42 silver badges55 bronze badges

I had this issue but it was two failures during build. One was the missing component but the other was a ButterKnife @BindView couldn’t find the view. Fixing this fixed the missing component. I assume any failed annotation processing will cause similar issues.

answered Jul 28, 2017 at 20:23

Matt Goodwin's user avatar

Try to run the application, the build will fail and you will get the option to import the classes then.
This happens because dagger only imports these classes during runtime and not at compile time.

answered Dec 24, 2017 at 23:14

Burhan Shakir's user avatar

1

In my case in presenter i didn’t use @Inject annotation for overridden method of data manager and etc.

 @Inject
 public RegisterPresenter(DataManager dataManager, SchedulerProvider 
             schedulerProvider, CompositeDisposable compositeDisposable) {
                super(dataManager, schedulerProvider, compositeDisposable);
}

Alien's user avatar

Alien

14.6k6 gold badges38 silver badges56 bronze badges

answered Aug 7, 2018 at 8:54

Mayuresh Deshmukh's user avatar

Double Check your annotations everywhere for prticular component and module. Mine problem was i was using @Named in module but not defining it in the constructor.

answered Oct 12, 2018 at 7:35

Arpit's user avatar

ArpitArpit

2971 gold badge4 silver badges13 bronze badges

Check this if you are migrating to Dagger Hilt

I was getting a similar error when trying to migrate my app from dagger.android to Dagger Hilt. Looks like the issue was an incompatibility between the library versions. What I ended up doing was to first update my current dagger.android setup to the latest release (2.28), before starting to add and configure Dagger Hilt dependencies.

answered Aug 4, 2020 at 21:52

Seven's user avatar

SevenSeven

3,2041 gold badge17 silver badges15 bronze badges

First, add this line to the dependencies in the buildscript in the Project build.gradle file.

 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

Second, add this line at the top in the Module: app build.gradle file

apply plugin: 'com.neenbedankt.android-apt'

answered Jun 7, 2016 at 13:57

s-hunter's user avatar

s-hunters-hunter

22.9k14 gold badges82 silver badges120 bronze badges

2

For the instance where I received this error, the reported error was off-the-mark in that an error with DaggerMyComponent was reported, but the root cause was that — elsewhere in the code — I had, mistakenly, used ButterKnife’s @BindView with a private view-type member; fixing this eliminated the error.

answered Apr 20, 2019 at 6:51

aandotherchars's user avatar

That’s very wired problem I face it! i don’t have any idea why this related to Dagger!

I use ButterKnife for binding views but some how in coding (Rush copy/paste!) i wrote two different views with same id like below (both view with fab id)

@BindView(R.id.fab)
FloatingActionButton fab;
@BindView(R.id.fab)
Toolbar toolbar;

After trying to run app throw this error on build tab

Compilation failed; see the compiler error output for details.

And compiler error is

error: cannot find symbol class DaggerApplicationComponent

I know it seems ridiculous but it happen to me and after fix ids my problem solved.

Fixed Code

@BindView(R.id.fab)
FloatingActionButton fab;
@BindView(R.id.toolbar)
Toolbar toolbar;

Hope to help some one.

UPDATE

Once again it happens for me after a year and it same id in RecyclerView Adapter ids

answered Feb 27, 2019 at 9:22

Radesh's user avatar

RadeshRadesh

12.8k3 gold badges50 silver badges63 bronze badges

1

While trying to integrate latest Dagger 2 version, I am facing problem of Dagger auto generation. Dagger is not auto generating DaggerAppComponent in spite of several Rebuilds and Make Module App process.

Application class:

public class BaseApplication extends Application
{
    private AppComponent appComponent;

    @Override
    public void onCreate()
    {
        super.onCreate();
        initAppComponent();
    }

    private void initAppComponent()
    {
        DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }

    public AppComponent getAppComponent()
    {
        return appComponent;
    }
}

AppComponent

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent
{
    void inject(BaseApplication application);
}

AppModule:

@Module
public class AppModule
{
    private BaseApplication application;

    public AppModule(BaseApplication app)
    {
        application = app;
    }

    @Provides
    @Singleton
    Context provideContext()
    {
        return application;
    }

    @Provides
    Application provideApplication()
    {
        return application;
    }
}

Dependency used:

compile 'com.google.dagger:dagger-android:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
androidTestCompile 'com.google.code.findbugs:jsr305:3.0.1'

Any help in this regard will be highly appreciated.

1. Overview

In this tutorial, we’ll review what compilation errors are. Then we’ll specifically explain the “cannot find symbol” error and how it’s caused.

2. Compile Time Errors

During compilation, the compiler analyses and verifies the code for numerous things, such as reference types, type casts, and method declarations, to name a few. This part of the compilation process is important, since during this phase we’ll get a compilation error.

Basically, there are three types of compile-time errors:

  • We can have syntax errors. One of the most common mistakes any programmer can make is forgetting to put the semicolon at the end of the statement. Some other mistakes include forgetting imports, mismatching parentheses, or omitting the return statement.
  • Next, there are type-checking errors. This is the process of verifying type safety in our code. With this check, we’re making sure that we have consistent types of expressions. For example, if we define a variable of type int, we should never assign a double or String value to it.
  • Finally, there’s the possibility that the compiler crashes. This is very rare, but it can happen. In this case, it’s good to know that our code might not be the problem, and that it’s an external issue instead.

The “cannot find symbol” error comes up mainly when we try to use a variable that’s not defined or declared in our program.

When our code compiles, the compiler needs to verify all the identifiers we have. The error cannot find symbol” means we’re referring to something that the compiler doesn’t know about.

3.1. What Can Cause the “cannot find symbol” Error?

There’s really only one cause; the compiler couldn’t find the definition of a variable we’re trying to reference.

But there are many reasons why this happens. To help us understand why, let’s remind ourselves what our Java source code consists of:

  • Keywords: true, false, class, while
  • Literals: numbers and text
  • Operators and other non-alphanumeric tokens: -, /, +, =, {
  • Identifiers: main, Reader, i, toString, etc.
  • Comments and whitespace

4. Misspelling

The most common issues are all spelling-related. If we recall that all Java identifiers are case-sensitive, we can see that the following would all be different ways to incorrectly refer to the StringBuilder class:

  • StringBiulder
  • stringBuilder
  • String_Builder

5. Instance Scope

This error can also be caused when using something that was declared outside of the scope of the class.

For example, let’s say we have an Article class that calls a generateId method:

public class Article {
    private int length;
    private long id;

    public Article(int length) {
        this.length = length;
        this.id = generateId();
    }
}

But we declare the generateId method in a separate class:

public class IdGenerator {
    public long generateId() {
        Random random = new Random();
        return random.nextInt();
    }
}

With this setup, the compiler will give a “cannot find symbol” error for generateId on line 7 of the Article snippet. This is because the syntax of line 7 implies that the generateId method is declared in Article.

Like in all mature languages, there’s more than one way to address this issue, but one way would be to construct IdGenerator in the Article class and then call the method:

public class Article {
    private int length;
    private long id;

    public Article(int length) {
        this.length = length;
        this.id = new IdGenerator().generateId();
    }
}

6. Undefined Variables

Sometimes we forget to declare the variable. As we can see from the snippet below, we’re trying to manipulate the variable we haven’t declared, which in this case is text:

public class Article {
    private int length;

    // ...

    public void setText(String newText) {
        this.text = newText; // text variable was never defined
    }
}

We solve this problem by declaring the variable text of type String:

public class Article {
    private int length;
    private String text;
    // ...

    public void setText(String newText) {
        this.text = newText;
    }
}

7. Variable Scope

When a variable declaration is out of scope at the point we tried to use it, it’ll cause an error during compilation. This typically happens when we work with loops.

Variables inside the loop aren’t accessible outside the loop:

public boolean findLetterB(String text) {
    for (int i=0; i < text.length(); i++) {
        Character character = text.charAt(i);
        if (String.valueOf(character).equals("b")) {
            return true;
        }
        return false;
    }

    if (character == "a") {  // <-- error!
        ...
    }
}

The if statement should go inside the for loop if we need to examine characters more:

public boolean findLetterB(String text) {
    for (int i = 0; i < text.length(); i++) {
        Character character = text.charAt(i);
        if (String.valueOf(character).equals("b")) {
            return true;
        } else if (String.valueOf(character).equals("a")) {
            ...
        }
        return false;
    }
}

8. Invalid Use of Methods or Fields

The “cannot find symbol” error will also occur if we use a field as a method or vice versa:

public class Article {
    private int length;
    private long id;
    private List<String> texts;

    public Article(int length) {
        this.length = length;
    }
    // getters and setters
}

If we try to refer to the Article’s texts field as if it were a method:

Article article = new Article(300);
List<String> texts = article.texts();

Then we’d see the error.

This is because the compiler is looking for a method called texts, and there isn’t one.

Actually, there’s a getter method we can use instead:

Article article = new Article(300);
List<String> texts = article.getTexts();

Mistakenly operating on an array rather than an array element is also an issue:

for (String text : texts) {
    String firstLetter = texts.charAt(0); // it should be text.charAt(0)
}

And so is forgetting the new keyword:

String s = String(); // should be 'new String()'

9. Package and Class Imports

Another problem is forgetting to import the class or package, like using a List object without importing java.util.List:

// missing import statement: 
// import java.util.List

public class Article {
    private int length;
    private long id;
    private List<String> texts;  <-- error!
    public Article(int length) {
        this.length = length;
    }
}

This code won’t compile, since the program doesn’t know what List is.

10. Wrong Imports

Importing the wrong type, due to IDE completion or auto-correction is also a common issue.

Think of a scenario where we want to use dates in Java. A lot of times, we could import a wrong Date class, which doesn’t provide the same methods and functionalities as other date classes that we might need:

Date date = new Date();
int year, month, day;

To get the year, month, or day for java.util.Date, we also need to import the Calendar class and extract the information from there.

Simply invoking getDate() from java.util.Date won’t work:

...
date.getDay();
date.getMonth();
date.getYear();

Instead, we use the Calendar object:

...
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);

However, if we’ve imported the LocalDate class, we won’t need additional code to provide us the information we need:

...
LocalDate localDate=date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
month = localDate.getMonthValue();
day = localDate.getDayOfMonth();

11. Conclusion

Compilers work on a fixed set of rules that are language-specific. If a code doesn’t stick to these rules, the compiler can’t perform a conversion process, which results in a compilation error. When we face the “cannot find symbol” compilation error, the key is to identify the cause.

From the error message, we can find the line of code where the error occurs, and which element is wrong. Knowing the most common issues that cause this error will make solving it quick and easy.

Недавние после обновления Android Studio (2.0.7) (может быть, это и есть причина), иногда при создании я получаю эту ошибку.

Идея заключается в том, что обычно компиляция идет хорошо, но иногда я получаю ошибку кинжала.

Возможно, это проблема в конфигурации кинжала?

Сама ошибка:


Executing tasks: [:app:assembleDebug]

Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2311Library UP-TO-DATE
:app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:app:prepareComDaimajiaSwipelayoutLibrary120Library UP-TO-DATE
:app:prepareComF2prateekRxPreferencesRxPreferences101Library UP-TO-DATE
:app:prepareComGithubAakiraExpandableLayout141Library UP-TO-DATE
:app:prepareComGithubAfollestadMaterialDialogsCore0842Library UP-TO-DATE
:app:prepareComGithubCastorflexSmoothprogressbarLibraryCircular120Library UP-TO-DATE
:app:prepareComJakewhartonRxbindingRxbinding030Library UP-TO-DATE
:app:prepareComPnikosisMaterialishProgress17Library UP-TO-DATE
:app:prepareComTrelloRxlifecycle040Library UP-TO-DATE
:app:prepareComTrelloRxlifecycleComponents040Library UP-TO-DATE
:app:prepareComWdullaerMaterialdatetimepicker211Library UP-TO-DATE
:app:prepareIoReactivexRxandroid110Library UP-TO-DATE
:app:prepareMeRelexCircleindicator116Library UP-TO-DATE
:app:prepareMeZhanghaiAndroidMaterialprogressbarLibrary114Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:compileDebugJavaWithJavac
/home/ungvas/AndroidDev/Projects/FW/paynet-android/app/src/main/java/md/fusionworks/paynet/ui/activity/BaseActivity.java:23: error: cannot find symbol
import md.fusionworks.paynet.di.component.DaggerActivityComponent;
^
symbol: class DaggerActivityComponent
location: package md.fusionworks.paynet.di.component
/home/ungvas/AndroidDev/Projects/FW/paynet-android/app/src/main/java/md/fusionworks/paynet/PaynetApplication.java:7: error: cannot find symbol
import md.fusionworks.paynet.di.component.DaggerApplicationComponent;
^
symbol: class DaggerApplicationComponent
location: package md.fusionworks.paynet.di.component
2 errors

Incremental compilation of 66 classes completed in 3.719 secs.
:app:compileDebugJavaWithJavac FAILED
:app:compileRetrolambdaDebug

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:app:compileDebugJavaWithJavac’.

    Compilation failed; see the compiler error output for details.

  • Try:
    Run with —stacktrace option to get the stack trace. Run with —info or —debug option to get more log output.

BUILD FAILED

Total time: 19.556 secs

Благодарю.

25 янв. 2016, в 11:21

Поделиться

Источник

17 ответов

Кажется, что это имеет какое-то отношение к инкрементной компиляции, добавленной в Gradle 2.10

Мне удалось исправить это, добавив следующую команду в gradle:

-Pandroid.incrementalJavaCompile=false

Вы можете добавить его в Android Studio в: Файл | Настройки | Создание, выполнение, развертывание | Компилятор добавляет его как параметр командной строки.

изменить как 2.0.0-beta3, плагин дает предупреждение о том, что этот параметр добавлен в DSL Gradle:

android {
    compileOptions.incremental = false
}

DanielDiSu
28 янв. 2016, в 11:46

Поделиться

Вам нужно обновить версию 2.11 для кинжала.

Блок build.gradle зависимостей должен выглядеть следующим образом.

dependencies {
    // Other dependencies should go here
    compile "com.google.dagger:dagger:2.11"
    annotationProcessor "com.google.dagger:dagger-compiler:2.11"
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'javax.inject:javax.inject:1'
}

Надеюсь, что это поможет.

Hiren Patel
27 сен. 2017, в 10:05

Поделиться

Изменения в 2017 году:

Android Studio Canary использует более новую версию Gradle, а apt-плагины могут не работать, заменены на annotationProcessor. Он может выйти из строя, несмотря на предупреждение компилятора о том, что он будет удален в будущей версии gradle.

Измените эту строку зависимостей:

apt 'com.google.dagger:dagger-compiler:2.7'

к

annotationProcessor 'com.google.dagger:dagger-compiler:2.7'

и удалите apt-плагин.

KATHYxx
31 авг. 2017, в 05:43

Поделиться

Последняя версия Dagger (2.8) вызывает эту ошибку. Убедитесь, что ваши зависимости указаны ниже.

apt 'com.google.dagger:dagger-compiler:2.7'
compile 'com.google.dagger:dagger:2.7'

fardown
28 янв. 2017, в 14:06

Поделиться

Файл- > InvalidateCaches/Restart работал у меня

D1 and 1ly
29 нояб. 2017, в 17:31

Поделиться

В моем случае ничего из этого не работает.

Выполните шаги для генерации класса DaggerApplicationComponent.

  • Очистить проект
  • Проект перестройки
  • Импортировать вручную с помощью Option + Return ИЛИ Alter + Enter, если у вас нет настроек автоматического импорта на лету в студии Android.

Готово

Hiren Patel
26 сен. 2017, в 11:58

Поделиться

У меня была аналогичная проблема, но по разной причине.
У меня была проблема только при попытке сгенерировать apk. В противном случае он работал правильно.
В моем случае проблема заключалась в том, что класс был в каталоге test вместо каталога main по какой-то неизвестной причине, я переместил его в main и работал.
Надеюсь, что это поможет кому-то.

PhpLou
22 фев. 2017, в 08:53

Поделиться

Убедитесь, что вы используете Java версии 1.7. Кроме того, если что-то еще сломано в вашем кинжальном конвейере, это также вызовет эту ошибку.

Horatio
13 нояб. 2016, в 22:52

Поделиться

Для случая, когда я получил эту ошибку, сообщенная ошибка была не в том, что сообщалось об ошибке с DaggerMyComponent, но основной причиной было то, что — в другом месте кода — я по ошибке использовал ButterKnife @BindView с закрытым членом типа view; исправление этой ошибки устранило ошибку.

aandotherchars
20 апр. 2019, в 08:13

Поделиться

Я использовал чистый модуль библиотеки Java, но использовал плагин kotlin и зависимости от кинжала, например:

build.gradle

apply plugin: 'kotlin'
dependencies {
    implementation "com.google.dagger:dagger:2.22.1"
    kapt "com.google.dagger:dagger-compiler:2.22.1"
}

Ошибка была, я пропустил, чтобы добавить плагин kotlin-kapt. Итак, мой файл build.gradle закончился так:

apply plugin: 'kotlin'
apply plugin: "kotlin-kapt" // make sure you added this line

dependencies {
    implementation "com.google.dagger:dagger:2.22.1"
    kapt "com.google.dagger:dagger-compiler:2.22.1"
}

Jorge E. Hernández
10 апр. 2019, в 17:49

Поделиться

С этой очень запутанной проблемой я сталкиваюсь! Я понятия не имею, почему это связано с Кинжалом!

Я использую ButterKnife для связывания представлений, но кое-как, как в кодировании (Rush copy/paste!) Я написал два разных представления с одинаковым идентификатором, как показано ниже (оба представления с идентификатором fab)

@BindView(R.id.fab)
FloatingActionButton fab;
@BindView(R.id.fab)
Toolbar toolbar;

После попытки запустить приложение выведите эту ошибку на вкладку сборки

Компиляция не удалась; см. вывод ошибки компилятора для деталей.

И ошибка компилятора

ошибка: не удается найти класс символов DaggerApplicationComponent

Я знаю, что это кажется смешным, но это случилось со мной, и после исправления проблемы моя проблема решена.

Надеюсь помочь кому-нибудь.

Radesh
27 фев. 2019, в 09:35

Поделиться

используйте одну и ту же версию кинжала для всех зависимостей кинжала. работал на меня.

implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVersion"
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"


//define version in main build.gradle
ext {
    daggerVersion = '2.11'
}

rajeswari ratala
30 янв. 2019, в 11:15

Поделиться

Дважды проверяйте свои аннотации на наличие компонентов и модулей. Моя проблема заключалась в том, что я использовал @Named в модуле, но не определял его в конструкторе.

Arpit
12 окт. 2018, в 07:59

Поделиться

В моем случае в @Inject я не использовал аннотацию @Inject для переопределенного метода менеджера данных и т.д.

 @Inject
 public RegisterPresenter(DataManager dataManager, SchedulerProvider 
             schedulerProvider, CompositeDisposable compositeDisposable) {
                super(dataManager, schedulerProvider, compositeDisposable);
}

Mayuresh Deshmukh
07 авг. 2018, в 10:27

Поделиться

Попробуйте запустить приложение, сборка завершится неудачно, и вы получите возможность импортировать классы.
Это происходит потому, что кинжал импортирует только эти классы во время выполнения, а не во время компиляции.

Burhan Shakir
25 дек. 2017, в 01:03

Поделиться

У меня была эта проблема, но во время сборки это были две ошибки. Одним из них был недостающий компонент, но другой был ButterKnife @BindView не смог найти представление. Исправлено исправление недостающего компонента. Я предполагаю, что любая неудачная обработка аннотаций вызовет аналогичные проблемы.

Matt Goodwin
28 июль 2017, в 20:23

Поделиться

Сначала добавьте эту строку к зависимостям в buildscript в файле проекта build.gradle.

 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

Во-вторых, добавьте эту строку вверху в файл Module: app build.gradle

apply plugin: 'com.neenbedankt.android-apt'

s-hunter
07 июнь 2016, в 14:46

Поделиться

Ещё вопросы

  • 0Firefox не запускает «Размер коробки: границы окна»?
  • 1Как прочитать гиперссылку изображения в Power Point с помощью c #
  • 0Создание объектов в куче через функцию класса
  • 1Перекрасить JPanel при нажатии клавиши. (Ява)
  • 0Передать значения столбцов таблицы ng-repeat в массив
  • 0HTML локальное хранилище нескольких ключей?
  • 0Сброс фильтров столбцов HTML-таблицы по клику
  • 0HTML-страница и весна
  • 1Я не могу обработать 5 ГБ текстовый файл при получении этой ошибки?
  • 1Android добавить «…» в конце textview _EDIT
  • 1Как добавить ActionListener к кнопке закрытия [duplicate]
  • 1Почему я не могу наследовать от частного класса / интерфейса?
  • 0Нужно ли изучать ООП, прежде чем изучать Angular JS?
  • 0фильтр вложенных массивов с помощью angularjs-checkboxes-with-angularjs
  • 0Отношение QVariant и QObject — Иерархия классов?
  • 1Я использую random.shuffle неправильно или это ошибка?
  • 1Введите выражения в JavaScript
  • 0C ++, изменить значения объекта структуры, принадлежащего классу
  • 1WPF Показать переменную в новом окне
  • 0Как только сдвинуть часть страницы с помощью меню?
  • 0Перезапись Codeigniter .htaccess для базы данных
  • 0как показать дату с daterange (2 даты) в sql
  • 1Функция сцепления не работает, когда внутри другой функции
  • 0Почему я получаю сообщение «неразрешенный внешний символ»?
  • 0доступ к коллекции внутри json объекта углового
  • 0ssl сертификат приводит к тому, что один файл не работает
  • 1Как преобразовать массив wchar_t в байтовый массив для Java с помощью Swig?
  • 1Метод Console.WriteLine в c # не записывает свой аргумент, но аргумент из другого класса
  • 1Android: проблема с использованием нескольких контекстных меню
  • 0Добавление активного класса для ссылки «Домой» JS
  • 1Удаление символов ASCII в строке
  • 1NullPointerException и «Достигнут предел глубины», отправляющий SOAP после первой попытки
  • 1Отображение значений внутри столбца панд
  • 0C ++ Как работает повышение духа паразитами
  • 0Mysqldb не устанавливается в колбу Приложение использую pycharm
  • 0Есть ли способ сделать элементы с абсолютным положением, чтобы взять ширину экрана?
  • 1ElmahR не ловит никаких исключений
  • 0Получить таблицу с подготовленным оператором, используя пользовательский ввод
  • 1Модификация XML из разных задач одновременно
  • 0алгоритмическая сложность следующего фрагмента кода
  • 1Как мне связаться с конкретным процессом в одном узле Erlang?
  • 0Angular — проверка новых данных и применение пользовательского класса или функции
  • 1Pyomo: KeyError: «Индекс» (0, 1, 1) «недопустим для индексированного компонента« x_ijl »»
  • 1Как минимизировать это расстояние быстрее с Numpy? (найти индекс сдвига, для которого два сигнала близки друг к другу)
  • 0Mysql агрегированная сумма построчно [дубликаты]
  • 1Интерфейс C #, содержащий свойство с типом enum
  • 1java.lang.invoke.MethodHandleStatics.newInternalError (MethodHandleStatics.java:97)
  • 1загрузка изображений из приложения Android на сервер с помощью веб-сервиса c #
  • 0Как создать идентификатор заказа, войдя в качестве гостя в Android-корзину приложений
  • 0Проблема кодирования CSS с моим логотипом и встроенным блоком навигации не выстраиваются

Сообщество Overcoder

Недавние после обновления Android Studio (2.0.7) (может быть, это и есть причина), иногда при создании я получаю эту ошибку.

Идея заключается в том, что обычно компиляция идет хорошо, но иногда я получаю ошибку кинжала.

Возможно, это проблема в конфигурации кинжала?

Сама ошибка:


Executing tasks: [:app:assembleDebug]

Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2311Library UP-TO-DATE
:app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:app:prepareComDaimajiaSwipelayoutLibrary120Library UP-TO-DATE
:app:prepareComF2prateekRxPreferencesRxPreferences101Library UP-TO-DATE
:app:prepareComGithubAakiraExpandableLayout141Library UP-TO-DATE
:app:prepareComGithubAfollestadMaterialDialogsCore0842Library UP-TO-DATE
:app:prepareComGithubCastorflexSmoothprogressbarLibraryCircular120Library UP-TO-DATE
:app:prepareComJakewhartonRxbindingRxbinding030Library UP-TO-DATE
:app:prepareComPnikosisMaterialishProgress17Library UP-TO-DATE
:app:prepareComTrelloRxlifecycle040Library UP-TO-DATE
:app:prepareComTrelloRxlifecycleComponents040Library UP-TO-DATE
:app:prepareComWdullaerMaterialdatetimepicker211Library UP-TO-DATE
:app:prepareIoReactivexRxandroid110Library UP-TO-DATE
:app:prepareMeRelexCircleindicator116Library UP-TO-DATE
:app:prepareMeZhanghaiAndroidMaterialprogressbarLibrary114Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:compileDebugJavaWithJavac
/home/ungvas/AndroidDev/Projects/FW/paynet-android/app/src/main/java/md/fusionworks/paynet/ui/activity/BaseActivity.java:23: error: cannot find symbol
import md.fusionworks.paynet.di.component.DaggerActivityComponent;
^
symbol: class DaggerActivityComponent
location: package md.fusionworks.paynet.di.component
/home/ungvas/AndroidDev/Projects/FW/paynet-android/app/src/main/java/md/fusionworks/paynet/PaynetApplication.java:7: error: cannot find symbol
import md.fusionworks.paynet.di.component.DaggerApplicationComponent;
^
symbol: class DaggerApplicationComponent
location: package md.fusionworks.paynet.di.component
2 errors

Incremental compilation of 66 classes completed in 3.719 secs.
:app:compileDebugJavaWithJavac FAILED
:app:compileRetrolambdaDebug

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:app:compileDebugJavaWithJavac’.

    Compilation failed; see the compiler error output for details.

  • Try:
    Run with —stacktrace option to get the stack trace. Run with —info or —debug option to get more log output.

BUILD FAILED

Total time: 19.556 secs

Благодарю.

4b9b3361

Ответ 1

Кажется, что это имеет какое-то отношение к инкрементной компиляции, добавленной в Gradle 2.10

Мне удалось исправить это, добавив следующую команду в gradle:

-Pandroid.incrementalJavaCompile=false

Вы можете добавить его в Android Studio в: Файл | Настройки | Создание, выполнение, развертывание | Компилятор добавляет его как параметр командной строки.

изменить как 2.0.0-beta3, плагин дает предупреждение о том, что этот параметр добавлен в DSL Gradle:

android {
    compileOptions.incremental = false
}

Ответ 2

Изменения в 2017 году:

Android Studio Canary использует более новую версию Gradle, а apt-плагины могут не работать, заменены на annotationProcessor. Он может выйти из строя, несмотря на предупреждение компилятора о том, что он будет удален в будущей версии gradle.

Измените эту строку зависимостей:

apt 'com.google.dagger:dagger-compiler:2.7'

к

annotationProcessor 'com.google.dagger:dagger-compiler:2.7'

и удалите apt-плагин.

Ответ 3

Вам нужно обновить версию 2.11 для кинжала.

Блок build.gradle зависимостей должен выглядеть следующим образом.

dependencies {
    // Other dependencies should go here
    compile "com.google.dagger:dagger:2.11"
    annotationProcessor "com.google.dagger:dagger-compiler:2.11"
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'javax.inject:javax.inject:1'
}

Надеюсь, что это поможет.

Ответ 4

Последняя версия Dagger (2.8) вызывает эту ошибку. Убедитесь, что ваши зависимости указаны ниже.

apt 'com.google.dagger:dagger-compiler:2.7'
compile 'com.google.dagger:dagger:2.7'

Ответ 5

Убедитесь, что вы используете Java версии 1.7. Кроме того, если что-то еще сломано в вашем кинжальном конвейере, это также вызовет эту ошибку.

Ответ 6

У меня была аналогичная проблема, но по разной причине.
У меня была проблема только при попытке сгенерировать apk. В противном случае он работал правильно.
В моем случае проблема заключалась в том, что класс был в каталоге test вместо каталога main по какой-то неизвестной причине, я переместил его в main и работал.
Надеюсь, что это поможет кому-то.

Ответ 7

В моем случае ничего из этого не работает.

Выполните шаги для генерации класса DaggerApplicationComponent.

  • Очистить проект
  • Проект перестройки
  • Импортировать вручную с помощью Option + Return ИЛИ Alter + Enter, если у вас нет настроек автоматического импорта на лету в студии Android.

Готово

Ответ 8

Файл- > InvalidateCaches/Restart работал у меня

Ответ 9

Я использовал чистый модуль библиотеки Java, но использовал плагин kotlin и зависимости от кинжала, например:

build.gradle

apply plugin: 'kotlin'
dependencies {
    implementation "com.google.dagger:dagger:2.22.1"
    kapt "com.google.dagger:dagger-compiler:2.22.1"
}

Ошибка была, я пропустил, чтобы добавить плагин kotlin-kapt. Итак, мой файл build.gradle закончился так:

apply plugin: 'kotlin'
apply plugin: "kotlin-kapt" // make sure you added this line

dependencies {
    implementation "com.google.dagger:dagger:2.22.1"
    kapt "com.google.dagger:dagger-compiler:2.22.1"
}

Ответ 10

Сначала добавьте эту строку к зависимостям в buildscript в файле проекта build.gradle.

 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

Во-вторых, добавьте эту строку вверху в файл Module: app build.gradle

apply plugin: 'com.neenbedankt.android-apt'

Ответ 11

У меня была эта проблема, но во время сборки это были две ошибки. Одним из них был недостающий компонент, но другой был ButterKnife @BindView не смог найти представление. Исправлено исправление недостающего компонента. Я предполагаю, что любая неудачная обработка аннотаций вызовет аналогичные проблемы.

Ответ 12

Попробуйте запустить приложение, сборка завершится неудачно, и вы получите возможность импортировать классы.
Это происходит потому, что кинжал импортирует только эти классы во время выполнения, а не во время компиляции.

Ответ 13

В моем случае в @Inject я не использовал аннотацию @Inject для переопределенного метода менеджера данных и т.д.

 @Inject
 public RegisterPresenter(DataManager dataManager, SchedulerProvider 
             schedulerProvider, CompositeDisposable compositeDisposable) {
                super(dataManager, schedulerProvider, compositeDisposable);
}

Ответ 14

Дважды проверяйте свои аннотации на наличие компонентов и модулей. Моя проблема заключалась в том, что я использовал @Named в модуле, но не определял его в конструкторе.

Ответ 15

используйте одну и ту же версию кинжала для всех зависимостей кинжала. работал на меня.

implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVersion"
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"


//define version in main build.gradle
ext {
    daggerVersion = '2.11'
}

Ответ 16

С этой очень запутанной проблемой я сталкиваюсь! Я понятия не имею, почему это связано с Кинжалом!

Я использую ButterKnife для связывания представлений, но кое-как, как в кодировании (Rush copy/paste!) Я написал два разных представления с одинаковым идентификатором, как показано ниже (оба представления с идентификатором fab)

@BindView(R.id.fab)
FloatingActionButton fab;
@BindView(R.id.fab)
Toolbar toolbar;

После попытки запустить приложение выведите эту ошибку на вкладку сборки

Компиляция не удалась; см. вывод ошибки компилятора для деталей.

И ошибка компилятора

ошибка: не удается найти класс символов DaggerApplicationComponent

Я знаю, что это кажется смешным, но это случилось со мной, и после исправления проблемы моя проблема решена.

Фиксированный код

@BindView(R.id.fab)
FloatingActionButton fab;
@BindView(R.id.toolbar)
Toolbar toolbar;

Надеюсь помочь кому-нибудь.

ОБНОВИТЬ

Еще раз это происходит для меня через год, и тот же идентификатор в идентификаторах адаптера RecyclerView

Ответ 17

Для случая, когда я получил эту ошибку, сообщенная ошибка была не в том, что сообщалось об ошибке с DaggerMyComponent, но основной причиной было то, что — в другом месте кода — я по ошибке использовал ButterKnife @BindView с закрытым членом типа view; исправление этой ошибки устранило ошибку.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error cannot find pspell
  • Error cannot find parameter
  • Error cannot find module webpack lib rules descriptiondatamatcherruleplugin require stack
  • Error cannot find module webpack cli package json
  • Error cannot find module webpack cli bin config yargs

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии