Android room shows the error AppDatabase_Impl does not exist - java

I am developing an app and add the room for database but it shows the error is
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.app.android/com.app.android.activities.AttendanceActivity}:
java.lang.RuntimeException: cannot find implementation for
com.app.android.db.AppDatabase. AppDatabase_Impl does not exist
In gradle file I have add every thing. My gradle file is shown below. I don't know. what is the problem. This code is working in another application. But it shows in this application. Kindly help me.
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
android {
useLibrary 'org.apache.http.legacy'
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
applicationId 'com.app.android'
minSdkVersion 14
targetSdkVersion 25
versionCode 16
// edumia versionCode 16
versionName "2.0.5"
// edumia versionName "2.0.5"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
debuggable true
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
repositories {
jcenter()
maven {
url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
}
maven {
url 'https://dl.bintray.com/ayz4sci/maven/'
}
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
dependencies {
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile group: 'org.apache.httpcomponents', name: 'httpclient-android', version: '4.3.5.1'
compile 'com.android.support:appcompat-v7:21.0.+'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
compile 'com.facebook.shimmer:shimmer:0.1.0#aar'
compile 'com.afollestad.material-dialogs:core:0.9.3.0'
compile 'com.afollestad.material-dialogs:commons:0.9.3.0'
compile 'com.facebook.stetho:stetho:1.4.1'
compile 'com.uphyca:stetho_realm:2.0.0'
compile 'com.evernote:android-job:1.1.11'
compile 'com.firebase:firebase-jobdispatcher:0.6.0'
compile 'com.android.support:design:25.0.0'
compile 'com.ss.bannerslider:bannerslider:1.6.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.ayz4sci.androidfactory:downloadprogress:1.0.2'
compile('com.alibaba.android:ultraviewpager:1.0.6#aar') {
transitive = true
}
compile 'android.arch.lifecycle:extensions:1.0.0-rc1';
compile 'android.arch.persistence.room:runtime:1.0.0-rc1';
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0-rc1';
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-rc1';
}
MainActivity.java
public class AttendanceActivity extends ActionBarActivity {
private Class_ class_;
private AppDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = AppDatabase.getDatabase(getApplicationContext());
database.classDao().removeAllUsers();
Class_ aClass = new Class_(1,"model");
database.classDao().addClass(aClass);
Log.d(TAG, "added success");
}
AppDatabase.java
public abstract class AppDatabase extends RoomDatabase{
private static AppDatabase INSTANCE;
public abstract ClassDao classDao();
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context, AppDatabase.class, "edumiadatabase")
//Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class)
// To simplify the exercise, allow queries on the main thread.
// Don't do this on a real app!
.allowMainThreadQueries()
// recreate the database if necessary
.fallbackToDestructiveMigration()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
Class_.java
public class Class_ {
#PrimaryKey
public int id;
public String Class_;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getClass_() {
return Class_;
}
public void setClass_(String class_) {
Class_ = class_;
}
public Class_(int id, String class_){
this.id=id;
this.Class_ = class_;
}
}
ClassDao.java
#Dao
public interface ClassDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void addClass(Class_ user);
#Query("delete from user")
void removeAllUsers();
}

I have added #Database(entities = {Class_.class}, version = 1) in AppDatabase.java . The #Database annotation for your database class, and #Entity for your entity. I have given as correct. Then the issue solved.

I faced the same problem even after adding correct dependency in my
build.gradle of my app module. My problem was ,I have used different module for separating database layer and I have moved my dependency to build.gradle of corresponding module solved my problem.
Hope this will helpful to someone else !!!

#Database annotation is missing
add annotation something like this
#Database(entities = [Articles::class], version = 1)
abstract class NewsDatabase : RoomDatabase() {
abstract fun articlesDao(): ArticlesDao
}
also for kotlin add following line to dependencies
kapt "android.arch.persistence.room:compiler:1.1.1"
also i was using kotlin and all my data class members were non nullable.
worked fine after i changed them to nullable types

Related

Passing Application Context in Activity in Dagger 2 (NullPointerException)

I am trying to pass Application context Activity in Dagger 2. Any bits of help is well appreciated!! I have provided my Logcat console at the end.
The project by Gregory Kick gives me the same problem as shown below at last error section. https://github.com/gk5885/dagger-android-sample
I have also tried to improve based on this issue: https://github.com/google/dagger/issues/832
Nothing worked! I know Application context is, actually, not needed in Activity because there is Activity context in the Activity. But just curious to learn how can I pass Application context in any classes (for instance, Activity)?
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
testBuildType "staging"
testOptions {
reportDir "$rootDir/test-reports"
resultsDir "$rootDir/test-results"
unitTests {
returnDefaultValues true
all {
// Sets JVM argument(s) for the test JVM(s).
jvmArgs '-XX:MaxPermSize=256m'
// You can also check the task name to apply options to only the tests you specify.
if (it.name == 'testDebugUnitTest') {
systemProperty 'debug', 'true'
}
}
}
}
defaultConfig {
applicationId "com.nexuslab.forensics.grr.nanny"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testHandleProfiling true
testFunctionalTest true
}
signingConfigs {
debugKey {
keyAlias 'android'
keyPassword 'android'
storeFile file('keys/platform.jks')
storePassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debugKey
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
staging {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compileOnly 'org.projectlombok:lombok:1.16.20'
annotationProcessor 'org.projectlombok:lombok:1.16.20'
//java vm based test
testImplementation 'org.hamcrest:hamcrest-core:1.3'
testImplementation 'junit:junit:4.12'
testImplementation 'org.powermock:powermock-api-mockito:1.6.5'
testImplementation 'org.powermock:powermock-module-junit4-rule-agent:1.6.5'
testImplementation 'org.powermock:powermock-module-junit4-rule:1.6.5'
testImplementation 'org.powermock:powermock-module-junit4:1.6.5'
testImplementation 'org.mockito:mockito-core:2.15.0'
//instrumentation test
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
androidTestImplementation 'com.android.support:support-annotations:27.1.0'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test:rules:1.0.1'
androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:2.1.3'
androidTestImplementation 'junit:junit:4.12'
//dagger 2
implementation 'com.google.dagger:dagger:2.14.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.14.1'
//to enable DaggerActivity, DaggerBroadcastReceiver, DaggerFragment etc classes
implementation 'com.google.dagger:dagger-android:2.14.1'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.14.1'
//support libraries with dagger 2
implementation 'com.google.dagger:dagger-android-support:2.14.1'
implementation 'com.android.support:support-v4:27.1.0'
}
Application class (NannyApplication.java)
package com.nexuslab.forensics.grr.nanny;
import android.app.Application;
import com.nexuslab.forensics.grr.nanny.di.component.DaggerNannyApplicationComponent;
/**
* Created by gaute on 3/25/18.
*/
public class NannyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
DaggerNannyApplicationComponent.builder().create(this);
}
}
MainActivity.java (Here, I want to inject context from NannyApplication.java)
package com.nexuslab.forensics.grr.nanny;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import javax.inject.Inject;
/**
* #author gaute
*/
public class MainActivity extends AppCompatActivity {
#Inject
NannyApplication nannyApplication;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
Utils.schedule(nannyApplication, HeartbeatService.class, Constants.HEARTBEAT_CHECK_INTERVAL);
finishAndRemoveTask();
}
}
Dagger Application Component (NannyApplicationComponent.java)
package com.nexuslab.forensics.grr.nanny.di.component;
import com.nexuslab.forensics.grr.nanny.NannyApplication;
import com.nexuslab.forensics.grr.nanny.di.module.NannyApplicationModule;
import javax.inject.Singleton;
import dagger.Component;
import dagger.android.AndroidInjector;
/**
* Created by gaute on 3/25/18.
*/
#Singleton
#Component(modules = NannyApplicationModule.class)
public interface NannyApplicationComponent extends AndroidInjector<NannyApplication> {
#Component.Builder
abstract class Builder extends AndroidInjector.Builder<NannyApplication> {
}
}
Application Module (NannyApplicationModule.java)
package com.nexuslab.forensics.grr.nanny.di.module;
import com.nexuslab.forensics.grr.nanny.NannyApplication;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import dagger.android.AndroidInjectionModule;
#Module(includes = AndroidInjectionModule.class)
public class NannyApplicationModule {
#Provides
#Singleton
NannyApplication getNannyApplication(NannyApplication nannyApplication) {
return nannyApplication;
}
}
Error, I got
03-27 19:08:37.107 10619-10619/com.nexuslab.forensics.grr.nanny E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nexuslab.forensics.grr.nanny, PID: 10619
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nexuslab.forensics.grr.nanny/com.nexuslab.forensics.grr.nanny.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] com.nexuslab.forensics.grr.nanny.NannyApplication.databaseList()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] com.nexuslab.forensics.grr.nanny.NannyApplication.databaseList()' on a null object reference
at com.nexuslab.forensics.grr.nanny.MainActivity.onStart(MainActivity.java:26)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1412)
at android.app.Activity.performStart(Activity.java:7015)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
I Can't use any sorts of constructor injection in an Activity as below.
private NannyApplication nannyApplication;
#Inject
public MainActivity() {
this.nannyApplication = nannyApplication;
}
That's why I used filed injection:
#Inject NannyApplication nannyApplication; //Problem here
This is a working solution.
Rule: For any Service Component T, we must provide T’s instance as a seedInstance into the AndroidInjector.Builder<T> class. It means if you do AndroidInjector.inject(this) inside MainActivity's lifecycle callback, you initialized seedInstance = mainActivity inside AndroidInjector.Builder<MainActivity> class.
This AndroidInjector.Builder<MainActivity>, you will see inside the DaggerNannyApplicationComponent's Builder inner class because, in the NannyApplicationComponent, you will gonna write
#Component.Builder /* Simply tells this Builder is DaggerNannyApplicationComponent’s inner Builder class */
abstract class Builder extends AndroidInjector.Builder<NannyApplication> {
}
The Sample project in Github: https://github.com/uddhavgautam/Dagger2ApplicationContextToActivity
NannyApplicationComponent.java
#Singleton
#Component(modules = {
AndroidSupportInjectionModule.class /* it makes Dagger generates DaggerNannyApplicationComponent */,
ApplicationBindingModule.class /* it generats AndroidInjector.Builder<MainActivity>, which
is used to inject requested dependencies by MainActivity */
})
public interface NannyApplicationComponent extends AndroidInjector<NannyApplication> {
#Component.Builder /* Simply tells this Builder is DaggerNannyApplicationComponent’s inner Builder class */
abstract class Builder extends AndroidInjector.Builder<NannyApplication> {
}
}
ApplicationBindingModule.java
#Module
public interface ApplicationBindingModule {
/* These two lines, actually, makes Dagger generates ApplicationBindingModule_MainActivity class */
#ContributesAndroidInjector
MainActivity mainActivity();
}
NannyApplicationModule.java
#Module
public class NannyApplicationModule {
}
MainActivity.java
//MainActivity is a consumer because it has requested nannyApplication using #Inject annotation
public class MainActivity extends DaggerAppCompatActivity {
#Inject
NannyApplication nannyApplication /* You got the ApplicationContext */;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// AndroidInjection.inject(this);
/* if Consumers want MainActivity instance then uncomment AndroidInjection.inject(this) line. Doing this makes MainActivity Consumer as well as Service component. Because it consumed nannyApplication but it has also provided (serviced) it's instance to the external world */
}
#Override
protected void onStart() {
super.onStart();
//check nannyApplication
Log.i("Cls-loader: ", nannyApplication.getClassLoader() + "");
}
}
NannyApplication.java
public class NannyApplication extends DaggerApplication {
#Override
public void onCreate() {
super.onCreate();
}
/**
* applicationInjector() gets called inside onCreate()
*/
#Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerNannyApplicationComponent
.builder()
.create(this);
}
}

Cannot resolve symbol generated AutoValue_Foo class inside pure java module in android project

I am trying to use AutoValue in a module that is written in pure Java that acts the domain module for my Android application. My application is composed of 3 layers, presentation, domain and data. Presentation and Data both have android dependencies, but domain does not.
Here is the AutoValue class data implementation :
import com.google.auto.value.AutoValue;
import org.jetbrains.annotations.Nullable;
import java.util.Date;
#AutoValue
public abstract class Trip {
public abstract int id();
public abstract String name();
public abstract int totalDistance();
#Nullable public abstract Date startDate();
#Nullable public abstract Date endDate();
public static Builder builder() {
return new AutoValue_Trip.Builder().totalDistance(0);
}
#AutoValue.Builder
public abstract static class Builder {
public abstract Builder id(int id);
public abstract Builder name(String name);
public abstract Builder totalDistance(int totalDistance);
public abstract Builder startDate(Date startDate);
public abstract Builder endDate(Date endDate);
public abstract Trip build();
}
}
Android Studio cannot find the generated AutoValue_Trip class, so it marks it as an error however, the project builds and runs just fine.
Here is my build.gradle of the domain module
buildscript {
repositories {
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.2.3'
classpath "net.ltgt.gradle:gradle-apt-plugin:0.12"
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: "net.ltgt.apt"
apply plugin: 'me.tatarka.retrolambda'
//noinspection GroovyUnusedAssignment
sourceCompatibility = 1.8
//noinspection GroovyUnusedAssignment
targetCompatibility = 1.8
configurations {
provided
}
sourceSets {
main {
compileClasspath += configurations.provided
}
}
dependencies {
def domainDependencies = rootProject.ext.domainDependencies
def domainTestDependencies = rootProject.ext.domainTestDependencies
apt domainDependencies.autoValue
compileOnly domainDependencies.autoValue
provided domainDependencies.javaxAnnotation
compile domainDependencies.javaxInject
compile domainDependencies.rxJava
compile domainDependencies.arrow
testCompile domainTestDependencies.junit
testCompile domainTestDependencies.mockito
testCompile domainTestDependencies.assertj
}
I have tried using a sourceSet as follows to add the generated build files and folders to the source path:
main {
java {
srcDirs += 'src/../build/generated'
}
}
But then I was getting compileJava errors.
Has anyone ran into this issue and how did you correct it? Additional info will be provided if necessary.

Unable to resolve this error: Multidex already enable

Information:Gradle tasks [:app:assembleDebug] Error:Execution failed for task ':app:transformClassesWithDexForDebug'. > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationExceptio
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion " 21.1.2"
defaultConfig {
applicationId "com.flikster.flikster"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "2g"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.squareup.picasso:picasso:2.5.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.joooonho:selectableroundedimageview:1.0.1'
compile 'com.makeramen:roundedimageview:2.2.1'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.0'
compile 'com.android.support:multidex:1.0.0'
compile 'com.google.android.gms:play-services:9.6.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.3.0'
compile 'com.pnikosis:materialish-progress:1.5'
}
Add below line to application tag in AndroidManifest.xml if you don't have any class which extends Application class
android:name="android.support.multidex.MultiDexApplication"
or add below to onCreate() method if you have any class which extends Application class
MultiDex.install(getBaseContext());
Create an Application Class
Initialize it MultiDex in onCreate()
public class MyApplication extends Application {
private static MyApplication applicationContext;
public static boolean isNotificationProcessing = false;
public MyApplication() {
applicationContext = this;
}
#Override
public void onCreate() {
super.onCreate();
MultiDex.install(getBaseContext());
}
}
Rebuild and run again

Dagger not generating Component classes

I have tried a great deal debugging this issue but unable to find the cause. Dagger simply doesn't create the DaggerComponent classes. I've checked SO for duplicates but none of the solutions provided worked.
project's build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'me.tatarka:gradle-retrolambda:3.2.3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath 'me.tatarka:gradle-retrolambda:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
jcenter {
url "http://jcenter.bintray.com"
}
mavenCentral()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
app's build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.hr.crux"
minSdkVersion 18
targetSdkVersion 23
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
retrolambda {
jvmArgs '-noverify'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
provided 'javax.annotation:jsr250-api:1.0'
apt 'com.google.dagger:dagger-compiler:2.2'
compile 'com.google.dagger:dagger:2.2'
provided 'javax.annotation:jsr250-api:1.0'
testCompile 'junit:junit:4.12'
}
HttpModule.java
#Module
public class HttpModule {
#Provides
#Singleton
Retrofit getRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/api/place/")
.build();
return retrofit;
}
}
HttpComponent.java
#Singleton
#Component(modules = {HttpModule.class})
public interface HttpComponent {
void inject(MainActivity activity);
}
Application.java
public class Application extends android.app.Application {
private static Application application;
private HttpComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
application = this;
appComponent = //Cannot find DaggerHttpComponent
}
public static Application getInstance() {
return application;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Inject
Retrofit retrofit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Dagger is failing to generate the component class in my Application class. I've tried clean building, I've tried invalidating cache but nothing works.
You can start a fresh project by yourself instead of following the tutorial project. If you do so, here is the solution.
These two lines are responsible to generate the compile-time framework in Dagger 2.
compile 'com.google.dagger:dagger:2.14.1'//generates framework in compile time
annotationProcessor 'com.google.dagger:dagger-compiler:2.14.1' //generates framework in compile time based on the annotations you provided.
Full setup Dagger
//dagger 2
compile 'com.google.dagger:dagger:2.14.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.14.1'
//to enable DaggerActivity, DaggerBroadcastReceiver, DaggerFragment etc classes
compile 'com.google.dagger:dagger-android:2.14.1'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.14.1'
//support libraries with dagger 2
compile 'com.google.dagger:dagger-android-support:2.14.1'
Note: You need to configure Annotation Process as provided in the screenshot below. You can do this File>Other Settings>Default Settings>search"Annotation processor"
As Other threads' Answers does NOT work for me:
I've answered here
Pref -> Editor -> File Types -> Ignore Files And Folders -> Remove "Dagger*.java;"

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.

Categories