java.lang.NoClassDefFoundError: dagger.internal.Preconditions android dagger2 - android

I am switching between two project using build flavor. I am using dagger2 and one project working fine but when switching another project and trying to run it showing below error:
java.lang.NoClassDefFoundError: dagger.internal.Preconditions
at common.di.DaggerAppComponent$Builder.appModule(DaggerAppComponent.java:35)
Here is my gradle dependency:
// Dependency Injection
annotationProcessor 'com.google.dagger:dagger-compiler:2.14.1'
implementation 'com.google.dagger:dagger:2.14.1'
compileOnly 'javax.annotation:jsr250-api:1.0'
The issue is mainly when adding appModule in AppComponent.
private AppComponent createAppComponent() {
return DaggerAppComponent.builder()
.appModule(new AppModule(this)) //Problem is here
.networkModule(new NetworkModule())
.build();
}

Finally, I have found the root cause. Its basically API level issue.
For android API level below 21 you need to add following dependency in build gradle file. Also change the Application class to MultiDexApplication like below:
In app build.gradle file:
Implementation 'com.android.support:multidex:1.0.3'
In you BaseApplication change Application class to MultiDexApplication:
public class BaseApplication extends MultiDexApplication {
#Override
public void onCreate() {
super.onCreate();
}
}

Related

Dagger 2 androidx fragment incompatible types

I'm using Dagger 2.21 and when I try to do
#Module
internal abstract class FragmentModule {
#ContributesAndroidInjector
internal abstract fun loginFragment() : LoginFragment
}
and
#Singleton
#Component(modules = [AndroidSupportInjectionModule::class, AppModule::class, ActivityModule::class, ViewModelBuilder::class, ViewModelModule::class, RepositoriesModule::class, ApiModule::class, FragmentModule::class])
interface AppComponent : AndroidInjector<PhotocoApplication> {
#Component.Builder
abstract class Builder : AndroidInjector.Builder<PhotocoApplication>()
}
I get this error:
/app/build/generated/source/kapt/debug/com/photoco/app/injection/module/FragmentModule_LoginFragment$app_debug.java:18: error: incompatible types: Class LoginFragment cannot be converted to Class extends Fragment
I have been searching and saw that using 2.21 and setting this gets it to work but no luck yet
android.useAndroidX=true ; android.enableJetifier=true
LoginFragment extends:
dagger.android.support.DaggerFragment()
With all this setup can't get it to build, am I missing something here? I can make it work with Activities using DaggerActivity but not with Fragments.
PhotocoApplication extends dagger.android.support.DaggerApplication
Thanks!
Fixed this issue by updating all dagger dependencies to 2.21, was missing android-support (was still using 2.16).
implementation 'com.google.dagger:dagger:2.21'
implementation 'com.google.dagger:dagger-android:2.21'
implementation 'com.google.dagger:dagger-android-support:2.21'
kapt "com.google.dagger:dagger-compiler:2.21"
kapt "com.google.dagger:dagger-android-processor:2.21"
I just had the same problem but with two non-Android classes: EventBus and a wrapper class around Android resources.
I tried the solution proposed by Emanuel Amiguinho even it had nothing to do with android-support and it got fixed. So I tried to remove the added dependency and retry, and magically built successfully again.
So I guess in my case it was some caching issue.

Dagger 2 component not generated

In my module, in my base Application class
component = DaggerCompClassComponent.builder()
.classModule(new ModuleClass()).build();
it can not find DaggerCompClassComponent.
I have on module build.gradle
apply plugin: 'com.neenbedankt.android-apt'
.........................
apt 'com.google.dagger:dagger-compiler:2.8'
compile 'com.google.dagger:dagger:2.8'
provided 'javax.annotation:jsr250-api:1.0'
and in Project build.gradle,
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
I have done build / rebuild / clean / restart project. I have a Component class where I inject objects and a ModuleClass where I provide objects to inject.
What can be the cause for not generating Dagger Component . class ?
EDIT:
This is my ModuleClass, adnotated with #Module:
#Provides
#Singleton
public Interceptor provideInterceptor() {
return new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("AppName-Android", BuildConfig.VERSION_NAME + "-" + BuildConfig.VERSION_CODE)
.addHeader("Content-Type", "application/json");
return chain.proceed(builder.build());
}
};
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient(Interceptor interceptor) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
return builder.build();
}
#Provides
#Singleton
Retrofit provideRetrofit(OkHttpClient client) {
return new Retrofit.Builder()
.baseUrl(BaseApplication.getRes().getString(R.string.api_base_url))
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
#Provides
#Singleton
WebServiceCall provideWebService(Retrofit retrofit) {
return retrofit.create(WebServiceCall.class);
}
And this is my Component Class:
#Component(modules = ModuleClass.class)
#Singleton
public interface ComponentClass {
void inject(Interceptor o);
void inject(OkHttpClient o);
void inject(Retrofit o);
void inject(WebServiceCall o);
}
When developing on Kotlin, you should add the following lines next to their annotationProcessor counterparts:
kapt 'com.google.dagger:dagger-android-processor:2.15'
kapt 'com.google.dagger:dagger-compiler:2.15'
and add apply plugin: 'kotlin-kapt' at the start of the same file.
That section looks like this for me:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt' // <- Add this line
apply plugin: 'io.fabric'
Update (March 29, 2020)
Inside your app-level build.gradle inside dependencies block, add these lines:
//dagger2
api 'com.google.dagger:dagger:2.24'
api 'com.google.dagger:dagger-android:2.24'
api 'com.google.dagger:dagger-android-support:2.24'
annotationProcessor 'com.google.dagger:dagger-compiler:2.24'
kapt 'com.google.dagger:dagger-compiler:2.24'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.24'
kapt 'com.google.dagger:dagger-android-processor:2.24'
compileOnly 'javax.annotation:jsr250-api:1.0'
implementation 'javax.inject:javax.inject:1'
Inside android block of app-level build.gradle,
kapt {
generateStubs = true
}
At the top of the app-level build.gradle, Do this in exactly below order.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
Finally, You need to configure Annotation Process as provided in the screenshot below. You can do this File>Other Settings>Settings for New Projects>search"Annotation processor"
After this, do from Menu Build > Rebuild. You are done!
Test:
#Component
public interface ApplicationComponent {
}
Now, you can use DaggerApplicationComponent that was generated at compile-time for your ApplicationComponent interface.
public class MyApplication extends Application {
ApplicationComponent applicationComponent = DaggerApplicationComponent.create();
}
Maybe you forgot to annotate ModuleClass with #Module ?
If you have several modules in your AndroidStudio (modules in terms of Android Studio, not Dagger), another possible reason of fail is that you've forgot to put annotation processors into the all modules' build.gradle.
We've divided our app into several modules, updated dependencies from using implementation to using api but forgot to handle annotation processors accordingly.
So, you can have this lines only in a root module:
api 'com.google.dagger:dagger-android:2.16'
// if you use the support libraries
api 'com.google.dagger:dagger-android-support:2.16'
But this ones should be specified in all modules dependencies:
annotationProcessor 'com.google.dagger:dagger-compiler:2.16'
// if you use injections to Android classes
annotationProcessor 'com.google.dagger:dagger-android-processor:2.16'
If Dagger2 can not generate its components it means that your code have some errors with Scopes/Modules. Check our your #Provides/Inject methods.
UPD:
You should inject your components into cases where you need instances of classes provided by module.
like
inject(MainActivity main);
In build.gradle's app, you need to add necessary dependencies for Dagger to generate corresponding classes, as below:
implementation 'com.google.dagger:dagger-android:2.21'
implementation 'com.google.dagger:dagger-android-support:2.21' // if you use the support libraries
annotationProcessor 'com.google.dagger:dagger-android-processor:2.21'
annotationProcessor 'com.google.dagger:dagger-compiler:2.21'
you should change dagger version which you are using.
refer full dagger document in this
There are some minor misconceptions/faults in your code above, here's a working implementation:
Application.java:
component = DaggerComponentClass.builder().classModule(new ModuleClass()).build();
The generated class will be named DaggerComponentClass, not DaggerCompClassComponent. If you can't run your app in Android Studio to get it built, try Build->Clean project and Build->Rebuild project in the menu. If everything is OK Dagger will have compiled DaggerComponentClass which will be located in the same package as ComponentClass.
ComponentClass.java:
#Component(modules = ModuleClass.class)
public interface ComponentClass {
void inject(AClassThatShouldGetInstancesInjected instance);
}
A Component in Dagger2 has methods named inject that receive the instance to get instances injected into it, not the other way around. In the code above the class AClassThatShouldGetInstancesInjected will typically call componentClass.inject(this); to get instances injected into itself.
ModuleClass.java:
#Module
public class ModuleClass {
#Provides
#Singleton
public Interceptor provideInterceptor() {/*code*/}
//Your Providers...
}
The Module is correct in your code, make sure its annotated.
If you are using Kotlin, make sure to add kapt (Kotlin annotation processor) Gradle plugin to your build script and use kapt Gradle dependency type instead of annotationProcessor for Dagger Compiler.
apply plugin: 'kotlin-kapt
kapt deps.daggercompiler
implementation deps.dagger
For anyone doing this in the year 2022 on Android Studio, if you want to just use some Dagger capabilities, you only need to add this in your Gradle dependencies:
implementation 'com.google.dagger:dagger:2.41'
kapt 'com.google.dagger:dagger-compiler:2.41'
then this on your plugins:
id 'kotlin-kapt'
You don't need to add anything else.
Now here's the key step: You need to do a clean (either in Gradle or just select Clean Project under Build menu) because for some reason incremental compilation is getting in the way.
Then rebuild your project.
If you created your Dagger components correctly you should see compilation errors at this point, or if you created them correctly the auto-completion with your component(s) should now work in the code editor.
api 'com.google.dagger:dagger-android:2.28.3'
api 'com.google.dagger:dagger-android-support:2.28.3'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.28.3'
Replace above with below dependencies in app level dependencies, if you have used above
api 'com.google.dagger:dagger:2.28.3'
annotationProcessor 'com.google.dagger:dagger-compiler:2.28.3'
I solved it by editing my dagger dependencies to this:
implementation "com.google.dagger:dagger:${versions.dagger}"
kapt "com.google.dagger:dagger-compiler:${versions.dagger}"
As Accepted Answer does NOT work for me:
This issue is related to Android Studio (V4.1.2 and up) and you can fix it by doing the below steps:
Pref -> Editor -> File Types -> Ignore Files And Folders -> Remove "Dagger*.java;"
Also If you see other Dagger regexs, remove them too.
Now android studio will find generated component class.
In my case it wasn't being created only in Instrumentation Testing, because I was missing
kaptAndroidTest "com.google.dagger:dagger-compiler:$rootProject.daggerVersion"
Of course I'm using Kotlin and $rootProject.daggerVersion is a property on my base build file. You can replace for whatever version or gradle dependency you desire and are missing.
Try this worked for me with Kotlin. Just this much in build.gradle (Module YourProject.app)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}
dependencies {
.....
implementation 'com.google.dagger:dagger-android:2.35.1'
kapt 'com.google.dagger:dagger-compiler:2.15'
implementation 'javax.inject:javax.inject:1'
.....
}
//add all the dependencies otherwise component class will not be generated.
implementation 'com.google.dagger:dagger-android:2.21'
implementation 'com.google.dagger:dagger-android-support:2.21'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.21'
implementation 'com.google.dagger:dagger:2.21'
annotationProcessor 'com.google.dagger:dagger-compiler:2.21'

Dagger 2: Error about subcomponents, but I don't have any subcomponents in my app

I'm trying to use Dagger 2 in my app. I keep getting this error:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
java.lang.IllegalArgumentException: #dagger.Module does not define an element subcomponents()
I don't use subcomponents at all in the app so I have no idea why this error is occurring. I have one module and one component. Module:
#Singleton
#Module
public class ApplicationModule {
private final WSTApplication application;
public ApplicationModule(WSTApplication application) {
this.application = application;
}
#Provides
public WSTApplication application() {
return this.application;
}
#Provides
public Context applicationContext() {
return this.application;
}
#Provides
Realm provideRealm() {
return Realm.getDefaultInstance();
}
#Provides
RealmHelper providesRealmHelper(final Realm realm) {
return new RealmHelper(realm);
}
#Provides
#Singleton
public WorkoutPresenter providesWorkoutPresenter(final RealmHelper helper) {
return new WorkoutPresenter(helper);
}
}
And my component:
#Singleton
#Component(modules={ApplicationModule.class})
public interface ApplicationComponent {
void inject (MainActivity activity);
WSTApplication application();
Context applicationContext();
Realm provideRealm();
RealmHelper providesRealmHelper(Realm realm);
WorkoutPresenter providesWorkoutPresenter(RealmHelper helper);
}
And here is the onCreate from my application:
#Override
public void onCreate() {
super.onCreate();
component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
I can't get DaggerApplicationComponent to stop being red, either, but I assume this is because the project isn't actually building because of this weird subcomponent error? I've tried using the underscore (Dagger_ApplicationComponent) but that doesn't help.
I tried Google but all I found was guides on how to use subcomponents in Dagger, which is not what I want. I don't want to use subcomponents. I just want to use the one component.
Also, just in case this matters, here is what I put in my build.gradle files:
In the project buildscript:
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
And in the app level build.gradle:
apply plugin: 'com.neenbedankt.android-apt'
and then down in the dependencies:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.google.dagger:dagger:2.1'
compile 'com.android.support:support-v4:24.2.1'
testCompile 'junit:junit:4.12'
apt 'com.google.dagger:dagger-compiler:2.7'
provided 'org.glassfish:javax.annotation:10.0-b28'
}
Thanks to anyone who can help me! I'm new to Dagger2 and even after reading several beginner guides, I still don't entirely get it (I was hoping that trying to use it would make things clearer...so far it's clear as an oil spill). Sorry in advance in the highly likely event that I'm making a stupid beginner mistake.
Why do you use com.neenbedankt.android-apt? As far as I know it is obsolete now.
The Dagger GitHub page explains how to use it within an Android project.
dependencies {
compile 'com.google.dagger:dagger:2.x'
annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
}
Here you can find Dagger releases for the dependencies versions.
I'm not sure if it solves your problem right away but you should definitely give it a try.
The error you're getting is from version skew between the Dagger API and the annotation processor: compile 'com.google.dagger:dagger:2.1' and apt 'com.google.dagger:dagger-compiler:2.7'. In this particular case, the compiler is looking for #Module.subcomponents(), but it's not in your version of #Module (version 2.1) because it wasn't added until 2.7.
tl;dr
The api and the annotation processor should always be the same version.

Dagger 2 inject error in AppCompatActivity

I'm newbie for Dagger.
Current I create sample project some snip code:
MyComponent.java
#PerActivity
#Component(modules = MyModule.class)
public interface MyComponent {
void inject(TutorialActivity activity);
}
MyModule.java
#Module
public class MyModule {
#Provides
Position providePosition() {
return new Position();
}
}
PerActivity.java
#Scope
#Retention(RUNTIME)
public #interface PerActivity {}
TutorialActivity.java
public class TutorialActivity extends AppCompatActivity{}
When compile project I get error:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> java.lang.IllegalArgumentException: expected one element but was: <android.support.v4.app.FragmentActivity, android.support.v4.app.TaskStackBuilder.SupportParentable>
So if I change TutorialActivity as:
public class TutorialActivity extends Activity{}
or even
public class TutorialActivity{} // Without extends
Then it will working normally.(I can see class generated by Dagger2).
Please help !
Thanks.
UPDATE
My project structure:
common module.
app module. (app module will use common module as depended in gradle).
In both build.gradle (common and app module) I added:
apt "com.google.dagger:dagger-compiler:${daggerVersion}"
compile "com.google.dagger:dagger:${daggerVersion}"
In build.gradle at common module:
provide "org.glassfish:javax.annotation:${javaxAnnotationVersion}"
An error only occurs if I have 2 module. (module app depended on common).
If I move my Component/Module to module common -> It work.
But when I move that to app module -> Error when compile.
I'm not sure that your issue is a problem with Dagger because I don't see you requesting any dependencies in your Android components.
Nonetheless you need this in your build.gradle to use the depdendency injection annotations.
provided 'javax.annotation:jsr250-api:1.0'
Thanks #plash for your answer.
After I re-check for both module.
I found I only added:
provide "org.glassfish:javax.annotation:${javaxAnnotationVersion}"
in common module.
After I added that provide for both module then compile success.(Dagger generated class.)

Test Error Maven RoboGuice [No implementation for "class" was bound]

I have an Android Project which contains two source folders src and test. In test, I have my test classes and some mock classes. I'm using RoboGuice dependency injection for Android in some class I wrote tests for.
The tests run perfectly fine in Eclipse on an emulator but fail using maven clean install.
No implementation for com.Store<com.MessageEvent> was bound.
The tests fail at setUp when using the injector.
mm = Guice.createInjector(new TestModule()).getInstance(MM.class);
And here is my binding module:
public class TestModule implements Module{
#Override
public void configure(com.google.inject.Binder binder) {
binder.bind(Context.class).toInstance(getContext());
binder.bind(Scheduler.class).to(MockScheduler.class);
binder.bind(EventManager.class).to(MockEventManager.class);
binder.bind(new TypeLiteral<Store<Message>>(){}).to(new TypeLiteral<JsonStore<Message>>(){});
binder.bind(new TypeLiteral<Store<MessageEvent>>(){}).to(new TypeLiteral<JsonStore<MessageEvent>>(){});
}
#Provides
JsonStore<MessageEvent> provideMessageEventJsonStore(Context context){
return new JsonStore<MessageEvent>(context, "message_events_test.json", MessageEvent.class);
}
#Provides
JsonStore<Message> provideMessageJsonStore(Context context){
return new JsonStore<Message>(context, "message_manager_test.json", Message.class);
}
}
Why would the exception be thrown while running tests in Maven but not in Eclipse?
"No implementation was bound" means that you need to add a line for this particuar class in your modules file.

Categories

Resources