Dagger2 component is not created - java

Here is the code....
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import javax.inject.Inject;
public class MainActivity extends AppCompatActivity {
#Inject
SampleModule sampleModule;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((SampleApp)getApplication()).getSampleComponent().inject(this);
sampleModule.simpleModel.setX(10);
}
}
SampleApp
import android.app.Application;
/**
* Created by pavan on 4/17/2017.
*/
public class SampleApp extends Application {
private SampleComponent sampleComponent;
#Override
public void onCreate() {
super.onCreate();
sampleComponent = DaggerSampleComponent.builder()
.sampleModule(new SampleModule(this))
.build();
}
public SampleComponent getSampleComponent(){
return sampleComponent;
}
}
SampleComponent
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by pavan on 4/17/2017.
*/
#Singleton
#Component(modules = {SampleModule.class})
public interface SampleComponent {
void inject(MainActivity activity);
}
SampleModule
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by pavan on 4/17/2017.
*/
#Module
public class SampleModule {
SimpleModel simpleModel;
SampleApp sampleApp;
public SampleModule(SampleApp sampleApp){
this.sampleApp = sampleApp;
}
#Provides
#Singleton
public SampleApp provideApplication(){
return sampleApp;
}
#Provides
#Singleton
public SimpleModel provideSimpleModelObj() {
return new SimpleModel();
}
}
SimpleModel
public class SimpleModel {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
Gradle Log
Error:(13, 10) error: com.uvr.organizer.myfilesorganizer.FileOrganizerModule cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.
com.uvr.organizer.myfilesorganizer.FileOrganizerModule is injected at
com.uvr.organizer.myfilesorganizer.LoginActivity.appScope
com.uvr.organizer.myfilesorganizer.LoginActivity is injected at
com.uvr.organizer.myfilesorganizer.AppComponent.inject(loginActivity)
Error:(14, 10) error: com.uvr.organizer.myfilesorganizer.FileOrganizerModule cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.
com.uvr.organizer.myfilesorganizer.FileOrganizerModule is injected at
com.uvr.organizer.myfilesorganizer.MainActivity.appScope
com.uvr.organizer.myfilesorganizer.MainActivity is injected at
com.uvr.organizer.myfilesorganizer.AppComponent.inject(mainActivity)
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 8.136 secs
Information:3 errors
Information:0 warnings
Information:See complete output in console
All my problem is about the file "DaggerSampleComponent" which is not at all getting created unless i delete all inject in interface.
Java version : 1.8
The same code seems working on my office Mac but not in my Windows. struggling a lot for this.
Can someone help me!!!
Thanks in advance.

When something goes wrong with your Dagger 2 setup, you will get a compile-time message in the Gradle console when you try and build (it's in the bottom right corner of Android Studio). The message will tell you what is wrong and give you a clue for how to fix it.
In your case, it looks like you have something like this inside your LoginActivity:
#Inject FileOrganiserModule fileOrganiserModule;
protected void onCreate(Bundle savedInstanceState) {
Dagger 2 modules and components are like scaffolding that helps you to request injection for the dependencies in your project. You normally shouldn't request injection of them by putting #Inject annotations on them.
If you have to create your module with a reference of the current Activity, you normally just create an instance of the module using the constructor:
void injectMembers() {
DaggerLoginComponent.builder().loginModule(new LoginModule(this));
}
Or you can use the new dagger.android classes to do that for you. A good example project for you to follow is in the Google Android Architecture Blueprints repo here

Related

Error: #dagger.android.ContributesAndroidInjector was used, but dagger.android.processor.AndroidProcessor was not found

I am trying to setup Dagger 2.12 and I'm getting this error:
error: #dagger.android.ContributesAndroidInjector was used, but dagger.android.processor.AndroidProcessor was not found on the processor path
Here's how I've configured Dagger:
My Application class:
public final class App extends android.app.Application implements HasActivityInjector {
#Inject
DispatchingAndroidInjector<Activity> activityInjector;
#Override
public void onCreate() {
super.onCreate();
DaggerAppComponent.builder().build().inject(this);
}
#Override
public AndroidInjector<Activity> activityInjector() {
return activityInjector;
}
}
ActivityBindingModule:
#Module
public abstract class ActivityBindingModule {
#ContributesAndroidInjector(modules = SearchActivityModule.class)
abstract SearchActivity searchActivity();
}
SearchActivityModule:
#Module
public class SearchActivityModule {
#Provides
public SearchActivityDelegate getDelegate(SearchActivity searchActivity) {
return searchActivity;
}
#Provides
public SearchActivityPresenter providePresenter(SearchActivity searchActivity) {
return new SearchActivityPresenter(new OtherDependency(), searchActivity);
}
}
AppModule:
#Module(includes = { AndroidInjectionModule.class, ActivityBindingModule.class })
public abstract class AppModule {
}
Does anyone know what could be causing this error?
Go to your module level build.gradle, under
annotationProcessor 'com.google.dagger:dagger-android-processor:[YOUR VERSION NUMBER]',
add:
kapt 'com.google.dagger:dagger-android-processor:[YOUR VERSION NUMBER]'.
the only solution for me was using old version of dagger (2.16)
kotlin version : 1.2.71
// dagger
implementation 'com.google.dagger:dagger-android:2.16'
implementation 'com.google.dagger:dagger-android-support:2.16'
kapt "com.google.dagger:dagger-compiler:2.16"
kapt "com.google.dagger:dagger-android-processor:2.16"
Probably you would have missed the following dependency.
annotationProcessor 'com.google.dagger:dagger-android-processor:' + yourDaggerVersion
For Java
Add this to your build.gradle
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
For Kotlin
Add this to your build.gradle
apply plugin: 'kotlin-kapt'
kapt "com.google.dagger:dagger-android-processor:$dagger_version"

Vaadin + Spring Boot errors: "Cannot enhance #Configuration" and "More than one Servlet Mapping defined"

I'm new to Spring and Vaadin. I'm trying to go through tutorial for views navigation.
I'd like to enable #Push in future to update views periodically with data fetched from DB.
The project is very, very simple. I use no configuration class nor any XML - only Java annotations.
Could anyone help me to fix the example code? Because I'm getting following warnings and I'm not sure what can be done with it and what will be the result of ignoring them.
First one is:
onClassPostProcessor : Cannot enhance #Configuration bean definition 'com.vaadin.spring.VaadinConfiguration' since its singleton instance has been created too early.
The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type:
Consider declaring such methods as 'static'.
And another one is only when I add compile("com.vaadin:vaadin-push") dependancy:
o.a.util.IOUtils : More than one Servlet Mapping defined.
WebSocket may not work org.apache.catalina.core.ApplicationServletRegistration
AppMain
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class AppMain {
public static void main(String[] args) {
SpringApplication.run(AppMain.class, args);
}
}
MyUI
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewDisplay;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.annotation.SpringViewDisplay;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
#Theme("valo")
#SpringUI(path = "/ui")
#SpringViewDisplay
public class MyUI extends UI implements ViewDisplay {
private Panel springViewDisplay;
#Override
protected void init(VaadinRequest request) {
final VerticalLayout root = new VerticalLayout();
root.setSizeFull();
setContent(root);
final CssLayout navigationBar = new CssLayout();
navigationBar.addStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
root.addComponent(navigationBar);
springViewDisplay = new Panel();
springViewDisplay.setSizeFull();
root.addComponent(springViewDisplay);
root.setExpandRatio(springViewDisplay, 1.0f);
}
#Override
public void showView(View view) {
springViewDisplay.setContent((Component) view);
}
}
DefaultView
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import javax.annotation.PostConstruct;
#SpringView(name = DefaultView.VIEW_NAME)
public class DefaultView extends VerticalLayout implements View {
public static final String VIEW_NAME = "";
#PostConstruct
void init() {
addComponent(new Label("This is the default view"));
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
// This view is constructed in the init() method()
}
}
build.gradle
buildscript {
ext { springBootVersion = '1.5.6.RELEASE' }
repositories { mavenCentral() }
dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories { mavenCentral() }
ext { vaadinVersion = '8.1.0' }
dependencies {
compile('com.vaadin:vaadin-spring-boot-starter')
compile("com.vaadin:vaadin-push")
compile("org.springframework.boot:spring-boot-starter-logging")
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports { mavenBom "com.vaadin:vaadin-bom:${vaadinVersion}" }
}
application.properties
server.port=8091

Dagger 2 giving error '...cannot be provided without an #Provides-annotated method'

I'm trying to build a simple android project for dagger 2 understanding. I currently have the component
MyComponent.java
#Component(modules = {MyModule.class})
public interface MyComponent {
MyModule provideModule();
}
MyModule.java
#Module
public class MyModule {
#Provides
Repo provideRepo(){
return new Repo();
}
}
Repo.java
public class Repo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I've added these to build.gradle for app
apt 'com.google.dagger:dagger-compiler:2.2'
compile 'com.google.dagger:dagger:2.2'
provided 'javax.annotation:jsr250-api:1.0'
Also in dependencies for project I've used this
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
When building the project, I'm getting this error
Error:(10, 14) error: com.example.bharatkulratan.daggernotworking.MyModule cannot be provided without an #Inject constructor or from an #Provides-annotated method.
The error reads out for missing #Provided annotation but provideRepo()
method is already having the annotation of #Provided. I'm unable to figure out the missing part. Please help.
Remove this
MyModule provideModule();
And add this in its place
Repo provideRepo();

Dagger 2 "Dagger" prefix component not able to compile? auto generated class

Im trying to use Dagger 2 on android. I previously had it working and i had an appModule injecting dependencies into specific classes in the app. My Issue is that iam getting the error
Error:(14, 55) error: cannot find symbol class DaggerAppComponent
which attempting to import. this is an autogenerated class
below are my Dagger specific dependencies in my build.gradle file
compile 'com.google.dagger:dagger-compiler:2.0.2'
compile 'com.google.dagger:dagger:2.0.2'
provided 'javax.annotation:jsr250-api:1.0'
Ive tried cleaning and rebuilding the app numerous times but the class wont generate. Ive also tried using
compile 'org.glassfish:javax.annotation:10.0-b28'
for my annotations but Iam having no luck still? If anyone can help me out id appreciate. Its kind of difficult to see exactly what is going on for me at present? Thanks
EDIT: Component code
this was working before and i just added 1 extra class to inject into?
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(RegHelper reghelper);
void inject(headerFooterRecViewAdapter headadapter);
void inject(SectionListExampleActivity seclistactivity);
}
This did the trick for me with the (current) latest dagger dependecies.
`dependencies{
...
compile 'com.google.dagger:dagger:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor "com.google.dagger:dagger-compiler:2.11"
}`
Please add
apt 'com.google.dagger:dagger-compiler:2.x'
to your app build.gradle file
Setting up a stand-alone project in Android Studio 2.3, I updated the default gradle files as follows to get the generated Component file. Added lines have comment // dagger2 addition
PROJECT build.gradle:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
// dagger2 addition
classpath 'com.android.tools.build:gradle:1.0.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.+'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
// dagger2 addition
mavenCentral()
maven{
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
APP MODULE build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' // dagger2 addition
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.demo.dagger2demo"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
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:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
// dagger2 addition
compile 'com.google.dagger:dagger:2.+'
apt "com.google.dagger:dagger-compiler:2.+"
}
You need to install this plugin https://bitbucket.org/hvisser/android-apt in order for Android Studio to see the Dagger Components.
I was having a similar issue with Dagger 2. I had an AppComponent and an ActivityComponent (being a subcomponent). And as soon as I would add a new inject() function in the AppComponent, I would get the above errors.
There was more errors besides the 'cannot find symbol' error but they were very vague and I couldn't debug my issues. After digging and researching stackoverflow and different tutorials, I realized I was using Dagger incorrectly. Specifically the way my AppComponent and ActivityComponent was setup.
I was under the assumption that I could inject my 'Activity' or 'Fragment' with both my AppComponent and ActivityComponent. This turned out to be wrong, at least I found out that it wasn't the right way of using Dagger.
My Solution:
AppComponent
#Singleton
#Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MyApp application);
void inject(ContextHelper contextHelper);
// for exports
MyApp application();
PrefsHelper prefsHelper();
}
App Module
#Module
public class AppModule {
private final MyApp application;
public AppModule(MyApp application) {
this.application = application;
}
#Provides #Singleton
public MyApp application() {
return this.application;
}
#Provides #Singleton
public PrefsHelper providePrefsHelper() {
PrefsHelper prefsHelper = new PrefsHelper(application);
return prefsHelper;
}
}
ActivityComponent
#ActivityScope
#Component (dependencies = {AppComponent.class}, modules = {ActivityModule.class})
public interface ActivityComponent {
void inject(MainActivity activity);
void inject(OtherActivity activity);
void inject(SomeFragment fragment);
}
ActivityModule
#Module
public class ActivityModule {
private final MyActivity activity;
public ActivityModule(MyActivity activity) {
this.activity = activity;
}
#Provides #ActivityScope
public ContextHelper provideContextHelper(MyApp application) {
// My ContextHelper depends on certain things from AppModule
// So I call appComponent.inject(contextHelper)
AppComponent appComponent = application.getAppComponent();
ContextHelper contextHelper = new ContextHelper(activity);
appComponent.inject(contextHelper);
return contextHelper;
}
}
Application
public class MyApp extends Application {
private AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
initializeDepInj();
}
private void initializeDepInj() {
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
}
public LockAppComponent getAppComponent() {
return appComponent;
}
}
Activity
public class MainActivity extends AppCompatActivity {
// I get it from ActivityModule
#Inject
ContextHelper contextHelper;
// I get it from AppModule
#Inject
PrefsHelper prefsHelper;
ActivityComponent component;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupInjection();
}
protected void setupInjection() {
MyApp application = (MyApp) getApplication();
component = DaggerActivityComponent.builder()
.appComponent(application.getAppComponent())
.activityModule(new ActivityModule(this))
.build();
component.inject(this);
// I was also doing the following snippet
// but it's not the correct way since the ActivityComponent depends
// on AppComponent and therefore ActivityComponent is the only
// component that I should inject() with and I'll still get classes
// that are provided by the AppComponent/AppModule
// application.getAppComponent().inject(this); // this is unneccessary
}
public ContextHelper getContextHelper() {
return contextHelper;
}
}
I don't know if it directly resolves your issue but it should at least shed some light on how to use Dagger properly.
Hope it helps.
I had the same problem on my setup, Android Studio 2.2 within the following application class:
public class NetApp extends Application {
private NetComponent mNetComponent;
#Override
public void onCreate() {
super.onCreate();
// Dagger%COMPONENT_NAME%
mNetComponent = DaggerNetComponent.builder()
// list of modules that are part of this component need to be created here too
.appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
.netModule(new NetModule("https://api.github.com"))
.build();
// If a Dagger 2 component does not have any constructor arguments for any of its modules,
// then we can use .create() as a shortcut instead:
// mNetComponent = com.codepath.dagger.components.DaggerNetComponent.create();
}
public NetComponent getNetComponent() {
return mNetComponent;
}
}
I'm using the following gradle declaration for dagger 2:
//Dagger 2
// apt command comes from the android-apt plugin
apt 'com.google.dagger:dagger-compiler:2.7'
compile 'com.google.dagger:dagger:2.7'
provided 'javax.annotation:jsr250-api:1.0'
I could solve the problem by rebuilding the complete project (with errors) and then adding the import of the DaggerNetComponent that was missing before.
Just add #Module to Api class & rebuild the project.
Hope you all doing well.
I was facing the same problem and spent a lot of time over stack overflow. At last I go through this and able to find solution. Briefly, You have to make some changes in your module level Gradle file. Please remove
apply plugin: 'com.neenbedankt.android-apt'
at the top of the file. And replace
apt 'com.google.dagger:dagger-compiler:2.11'
with
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
After that rebuild your project and you will be able to import your Dagger prefix classes. Hopw it will help you out.

Spring4 Boot WebService Controller not working with Gradle Tomcat Plugin

I am trying to make a simple Spring4 WebService here is a Gist with the basic code
https://gist.github.com/jrgleason/1e23b694e0facc123caa
It seems to start ok but when I access http://localhost:8080/itext I get a 404 exception. Can someone please help me with what is wrong? Is it because I am using the boot plugin?
Your application is working, check this url: http://localhost:8080/
Change you bean for http://localhost:8080/itext
#RestController
public class GreetingController {
#RequestMapping("/itext")
public String test(){
System.out.println("Test");
return "Test";
}
}
In Spring Boot Tomcat is embedded by default, there is no need to configure tomcat.
The problem is that Spring-Boot does not seem to play nice with the tomcat-plugin (A response that can get it working will steal the star!). As noted above you can reduce to just using the spring-boot...
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.1.RELEASE")
}
}
apply plugin: 'war'
apply plugin: 'spring-boot'
war { baseName='itext' }
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
If you do this, however, you will also need to change the Application.java to something like this....
package com.gleason.itext;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<Application> applicationClass = Application.class;
}

Categories