Android Dagger not building - android

I have already added Dagger into my application. Now I am facing the following error after updating Android studio and project updated to the latest AndroidX version.
error: [RefersToDaggerCodegen] Don't refer to Dagger's internal or generated code
(see https://errorprone.info/bugpattern/RefersToDaggerCodegen)
How to solve this build error.
Edit:
I am trying to inject dagger like the below
((App) appContext).getApplicationComponent().inject(this);
And inside of the interface
#SuppressWarnings({"RefersToDaggerCodegen"})
#Singleton
#Component(modules = {
ApplicationModule.class,
DatabaseModule.class,
NetworkModule.class,
QuranDataModule.class,
QuranPageModule.class } )
public interface ApplicationComponent {
#SuppressWarnings("RefersToDaggerCodegen")
void inject(QuranDataProvider quranDataProvider);
Edit 2
I have initialize the component like the following:
#SuppressWarnings("RefersToDaggerCodegen")
protected ApplicationComponent initializeInjector() {
return DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
Still facing the same issue.

The problem with my project is I am using dagger old version not too old but not latest. So I updated kotlin version and Dagger version to the following
kotlinVersion = '1.3.31'
daggerVersion = '2.15'
And in your gradle-wrapper.properties please update the distribution url like below
distributionUrl=https\://services.gradle.org/distributions/gradle-5.2-all.zip
And finally update the errorprone version also
classpath "net.ltgt.gradle:gradle-errorprone-plugin:0.8"
I have done all the above steps. Now I am able to build my application successfully.
Thanks for the help #EpicPandaForce

Related

Android multi-SDK project debug build

How to add a debug-mode specific functionality into an Android app which is broken into several SDKs?
Lets say I need to add an OkHttp interceptor to all OkHttp clients to all SDKs. But it has to be added only into the app's debug build. However, when the app is broken into several SDKs, they are published as release builds even if the main app is built in the debug mode. Thus, the debug-specific interceptors inside the SDKs would not be added to the OkHttp clients.
How to overcome this issue? I was thinking to take advantage of dependency injection (Koin) and pass Build type information from the app where Koin is started, but not sure Koin supports this feature.
You can select what build variant is active of each of the modules of your application.
https://developer.android.com/studio/build/build-variants
You can use getAll() in Koin for your purposes.
moduleb:
Domain:
interface Interceptor
class InterceptorFactory(val interceptors: List<Interceptor>) // Here you have a list of all interceptors from all modules
class HeadersInterceptor : Interceptor
Koin:
object BKoin {
val network2: Module
get() = module {
single<HeadersInterceptor>() bind Interceptor::class
single<InterceptorFactory> {
InterceptorFactory(getAll<Interceptor>())
}
}
}
module app:
define your objects
class OtherInterceptor : Interceptor
declare them
object AKoin {
val network1: Module
get() = module {
single<OtherInterceptor>() bind Interceptor::class
}
}
init Koin
startKoin {
val app = modules(
listOf(
BKoin.network2,
AKoin.network1
)
)
Log.d("TUT", "${app.koin.get<InterceptorFactory>().interceptors.map { it::class.simpleName }}")
}
Gradle:
dependencies {
implementation project(':moduleb')
}

Dagger not see my own generated dependency

I have an issue with Dagger and my own generated code.
Assumptions:
I need to generate my own dagger component for UI tests purpose
I have my own Gradle's module for annotation processing which provides dagger component with dependencies. Call this GeneratedTestCoreComponent. This class is generated correctly
GeneratedTestCoreComponent is built at \build\generated\source\kapt\debug\...
GeneratedTestCoreComponent is used in dagger component, smth like this
#Component(modules = [UiTestModule::class],
dependencies = [GeneratedTestCoreComponent::class])
interface TestUiComponent {}
My annotation processor module is correctly added to gradle
implementation project(path: ':processor')
kapt(name: 'processor')
The issue is. During compilation I get below error
TestUiComponent.java:6: error: cannot find symbol
#com.dagger.Component(modules = {com.xxx.xxx.UiTestModule.class}, dependencies = {GeneratedTestCoreComponent.class})
symbol: class GeneratedTestCoreComponent
TestUiComponent.java:8: error: [ComponentProcessor:MiscError] com.dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public abstract interface TestUiComponent
Additional info.
When I copy GeneratedTestCoreComponent class from build directory to src (keeping the same package) and disable my processor, then everything works fine
Try changing kapt(name: 'processor') into kapt project(':processor')

Note: Failed to read get kotlin metadata for [Ljava.lang.Object;#79d6c4df

I keep getting this error.
I am working on a project and in the middle of development, I decided to migrate to Android X.
I get the error below:
Note: Failed to read get kotlin metadata for [Ljava.lang.Object;#79d6c4df
There is the same error in a entity file and 4 of the same error in the respective DAO as well.
Here is the code of DAO:
#Dao
public interface FlockDao{
#Query("SELECT * FROM flock_table")
LiveData<List<Flock>> getAllFlocks();
#Query("SELECT * FROM flock_table WHERE fid IN (:flockIds) LIMIT 1")
Flock loadFlockById(int[] flockIds);
#Insert
void insert(Flock flock);
#Update
void update(Flock flock);
#Delete
void delete(Flock flock);
}
And my entity is:
#Entity
public class Flock{
#PrimaryKey(autoGenerate = true)
private int fid;
#ColumnInfo(name = "user_id")
private int uid;
#ColumnInfo(name = "name")
private String name;
#ColumnInfo(name = "capacity")
private int capacity;
#ColumnInfo(name = "type")
private String type;
#ColumnInfo(name = "arrived")
private Date arrived;
.....rest of the code is omitted, there are constructor, setters and getters
}
I updated my Room depency to 2.1.0-alpha05 and got the same problem. Returning to 2.1.0-alpha04 solved mine.
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha04'
UPDATE
If you really want to use Room version 2.1.0-alpha05, add the following depency to your project repository:
maven { url 'https://kotlin.bintray.com/kotlinx/' }
Reference: AndroidX Room Release Notes
UPDATE
I tried 2.1.0-alpha06.
implementation 'androidx.room:room-runtime:2.1.0-alpha06'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha06'
Then I add the depency to my project repository,
maven { url 'https://kotlin.bintray.com/kotlinx/' }
There was na error but it compiled. I tested my app in real device for weeks and there wasn’t any issue running my app. My Room database is working fine.
I solved this issue by downgrading to:
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha04'
Solved!
//Downgraded to alpha04.
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha04'
// Other dependencies are..
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.1.0-alpha03'
implementation 'androidx.lifecycle:lifecycle-livedata:2.1.0-alpha03'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.1.0-alpha03'
// Removed this from project level gradle.
maven { url "https://kotlin.bintray.com/kotlinx/" }
Don't forget to Clean & Rebuild the project after these changes
Like most errors that have something to do with Room, the error message that pops up the most is most unlikely to be your problem. For me it helped to raise the max Error count by adding :
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xmaxerrs" << "1000"
}
}
and then executing the gradle task:
:app compileDebugJavaWithJavac
Then you will get a large list of errors, in your case the
Note: Failed to read get kotlin metadata for [Ljava.lang.Object;#79d6c4df
But somewhere in that list are your real errors like a wrong query or something like that.
Fix those errors and rebuild the project, that works most of the time, but sometimes you have to invalidate the cache and restart Android Studio.
Invalidate caches and restart solved my problem. My room version is 2.1.0-alpha06 and I have also add the following dependency to my project repository:
maven { url 'https://kotlin.bintray.com/kotlinx/' }
I got the same error, I updated the room libraries, but issue not fixed,
then I did below steps, ... after that problem solved,
Step 1: Check #DataBase class in your project and check all tables (entities) are inserted
Step 2: Increment version number
Step 3: Add ".fallbackToDestructiveMigration()" before .build().
Don't forget to Clean & Rebuild the project after these changes
As I was typing this answer, I was notified of 2.1.0-alpha07. It resolved all errors. Going back to 2.1.0-alpha06 broke the build again.
It turns out the new version resolved the errors for me.
Before trying to resolve the error, try updating Android Studio first. After updating Gradle, all dependencies, and AS from 3.3.2 to 3.4, I found errors I haven't encountered before, like
error: Room cannot pick a constructor since multiple constructors are suitable. Try to annotate unwanted constructors with #Ignore.
error: Cannot find setter for field.
There are multiple good constructors and Room will pick the no-arg constructor. You can use the #Ignore annotation to eliminate unwanted constructors.
error: Not sure how to convert a Cursor to this method's return type.
Once I fixed them, the build was successful and the app ran. I didn't need to add any additional maven repos mentioned in the accepted answer.
Adding import androidx.room.Dao; and then re-importing it did the trick for me.
I solved by adding this to build.gradle (Module)
androidTestImplementation "androidx.arch.core:coretesting:$rootProject.archLifecycleVersion"
In my build.gradle(Project)
ext {
roomVersion = '2.1.0-alpha06'
archLifecycleVersion = '2.0.0'
}
Just change room_version in your gradle_module file in dependency block and change other room associated libraries you need. Use https://developer.android.com/jetpack/androidx/releases/room#2.2.0-alpha01 as an example. Try to use latest stable version of room.
I have the same error and i used version 2.1.x-alpha
and after updated to 2.2.3
the new version reported the error correctly and it was that one of my entities didn't have primary key
I came across the same problem and fixed it by override the equals & hashCode methods of the object.
A possible solution for your case:
#Override
public int hashCode() { return (27 * fid + (name!= null ? name.hashCode() : 0)); }
And
#Override
public boolean equals(#Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof Flock)) return false;
Flock flock = (Flock) obj;
if(fid != flock.fid) return false;
return name != null ? name.equals(flock.name) : flock.name == null;
}
you will also need find a solution for the Date usage in Room, Room doesn't have a build in solution for a Date variable.

Providing Injection for AndroidX Fragment with Dagger2?

I'm having some issues trying to provide an Injection to an AndroidX fragment, and I'm not sure what the exact issue is, and how to fix it. The app refuses to build, giving the following error:
error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<? extends androidx.fragment.app.Fragment>,javax.inject.Provider<dagger.android.AndroidInjector.Factory<? extends androidx.fragment.app.Fragment>>> cannot be provided without an #Provides-annotated method.
Here's the method to provide the Injection in the Fragment:
private fun performDependencyInjection() = AndroidSupportInjection.inject(this)
The fragment's parent Activity implements HasSupportFragmentInjector:
class MainActivity : BaseActivity(), MainMVPView, HasSupportFragmentInjector {
#Inject
internal lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
...
override fun supportFragmentInjector() = dispatchingAndroidInjector
}
I'm completely lost as to where to solve this error from here. It doesn't appear that there is much current documentation for using Dagger2 with AndroidX.
I do feel it is important to note I enabled AndroidX and Jetifier through
gradle.properties:
android.useAndroidX=true
android.enableJetifier=true
However, nothing had changed after a clean and rebuild of the project.
What is the proper way to provide an Injection to an AndroidX fragment using Dagger2?
Edit: For the record, this is on Dagger 2 version 2.19. If I switch to using 2.16, everything works fine.
This is due to a mismatch in the Jetifier sources, as you can see from the below code:
# Androidx compatible dagger
{
"from": { "groupId": "com.google.dagger", "artifactId": "dagger-android-processor", "version": "2.16" },
"to": { "groupId": "com.google.dagger", "artifactId": "dagger-android-processor", "version": "2.16" }
}
From the release note of dagger-2.19:
In the next release (2.20), we will remove the old format. This will
allow us to support AndroidX packages better.
So for now you either have to stick with version 2.16 or wait for the 2.20 release.

Dagger 2 using classes generated by another library

I have a homemade library that generates DataMapper classes.
They are generated with #Singleton and #Inject annotations to be able to inject them where i need them.
But where it doesn't work is when Dagger tries to create the dependency tree, this error shows :
:data:kaptGenerateStubsDebugKotlin
e: /Users/me/myproject/data/build/tmp/kapt3/stubs/debug/com/myproject/data/di/DataComponent.java:11: error: [Dagger/MissingBinding] error.NonExistentClass cannot be provided without an #Inject constructor or an #Provides-annotated method.
public abstract com.myproject.domain.repository.ContentRepository contentRepository();
^
error.NonExistentClass is injected at
com.myproject.data.repository.ContentDataRepository.<init>(…, myGeneratedDataMapper, …)
com.myproject.data.repository.ContentDataRepository is injected at
com.myproject.data.di.module.DataModule.contentRepository(contentDataRepository)
com.myproject.domain.repository.ContentRepository is provided at
com.myproject.data.di.DataComponent.contentRepository()
:data:kaptDebugKotlin
:data:kaptDebugKotlin FAILED
Involved classes are :
DataModule (module for dagger)
#Module
class DataModule {
#Provides
#Singleton
fun contentRepository(contentDataRepository: ContentDataRepository): ContentRepository = contentDataRepository
}
DataComponent (component for dagger):
#Singleton
#Component(modules = [DataModule::class])
interface DataComponent {
fun contentRepository(): ContentRepository
}
ContentDataRepository
#Singleton
class ContentDataRepository #Inject constructor(
private val myGeneratedDataMapper: MyGeneratedDataMapper
) : ContentRepository {
...
}
MyGeneratedDataMapper
#Singleton
class MyGeneratedDataMapper #Inject constructor() {
...
}
The thing is, if i disable kapt of dagger dependency in gradle.build, then build, then enable it, then build, it works.
If i do a clean + build, it doesn't work, same error.
I want to make it work in one row.
I don't know if you are using AS3.2 or AS3.3 with androidX artifacts or not but Maybe this is the case with you too.
so when i migrated to androidX artifacts in AS3.2 i got hit with bunch of NonExistentClass errors ends the build with
kaptGenerateStubsDebugKotlin
:data:kaptDebugKotlin
:data:kaptDebugKotlin
I finally found out that it has something to do with Dagger itself and degraded the version from 2.17 to 2.16 now the latest version of Dagger2 is 2.18 which i can't use due to this bug / feature [they forgot about].
Update:
i found the solution and it just came today so here is the issue tracker link:
https://issuetracker.google.com/issues/115738511
so the bug was not in the Dagger but it was with Jetifier and i totally ignored the fact that it was set enabled during migration
here's the solution i copied from the link:
Sorry jetifier beta01 was not binary compatible with alpha10.
We have published beta02 that should fix this issue.
Please try:
buildscript { dependencies {
classpath 'com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta02' } }
You're probably not going to like my answer but the order is kinda random.
Look at this thread for some more explaining and maybe some more guidance but, if you want to verify you are running first look at Gradle plugins and how to use them

Categories

Resources