Unable to build when Added new Activity in project having Hilt - Android - android

In my project, using dagger-Hilt
just by adding a new activity, it shows an error
:app:kaptDebugKotlin
[Hilt]
java.lang.reflect.InvocationTargetException (no error message)
but before adding a new activity, the whole project works fine
Activity :->
#AndroidEntryPoint
class SplashScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
}
}
my build.gradle
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"
classpath("com.google.dagger:hilt-android-gradle-plugin:2.38.1")

I have reproduced your issue. The real problem is with versions,your kotlin version is not compatible with hilt plugin version and hilt library version. Here are the few changes you need to do.
In project build.gradle, update hilt plugin version to 2.42
classpath("com.google.dagger:hilt-android-gradle-plugin:2.42")
In app build.gradle, update to latest versions like below.
implementation("com.google.dagger:hilt-android:2.42")
kapt("com.google.dagger:hilt-android-compiler:2.42")
kapt "androidx.hilt:hilt-compiler:1.0.0"
Hilt lifecycle module not required in latest hilt version.
You should remove the below line in build.gradle and remove all androidx.hilt.lifecycle.ViewModelInject imports in your project.Other wise it will throw error
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02"

Related

Android Hilt won't work with plugins added

I have questions about android hilt.
I have added hilt plugin.
//build.gradle(:project)
buildscript {
ext.hilt_version = '2.37'
dependencies {
...
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
}
}
//build.gradle(:app)
plugins {
...
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
dependencies {
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-compiler:$hilt_version"
}
//MyApplication.kt
#HiltAndroidApp
class MyApplication : Application() {...}
When I build the project,
I get the error message saying
"Expected #HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin?"
Do you have any idea?
I am also having same problem in my new projects. This error had gone after lowering kotlin version to 1.5.10. I think hilt has compatibility issues with latest kotlin plugin.
As mentioned by others, Kotlin 1.5.20 has a bug in Kapt which causes this issue.
It is fixed in 1.5.21. Just increase the version and you're good.
There is a bug in 1.5.20
To avoid this bug there is a workaround.
in build.gradle (app) file paste this code below.
generally, in the hilt Gradle plugin, these options are set automatically. in 1.5.20 it is not. if you set it manually it will resolve the issue.
kapt {
javacOptions {
option("-Adagger.fastInit=ENABLED")
option("-Adagger.hilt.android.internal.disableAndroidSuperclassValidation=true")
}}

Hilt + view model dont build

I have ViewModel
#HiltViewModel
class WControlViewModel #Inject constructor(
private val getProfile: GetProfile,
private val getHistory: GetHistory,
) : ViewModel() {...}
Activity
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val vModel: WControlViewModel by viewModels()
Application
#HiltAndroidApp
class WControlApp :Application()
But project not build, error :
return DefaultViewModelFactories.getActivityFactory(this);
^
required: ComponentActivity,Factory
found: Hilt_MainActivity
reason: actual and formal argument lists differ in length
I had the same issue, which I resolved by ensuring the hilt plugin version was upgraded. In my case I went from 2.33-beta to 2.35.1
So in the dependency in your project’s root build.gradle file
classpath "com.google.dagger:hilt-android-gradle-plugin:2.35.1"
You can find the latest version numbers here: https://mvnrepository.com/artifact/com.google.dagger/hilt-android-gradle-plugin
I had faced same issue so, I changed my project level dependency and app level dependency.
Try this
in App Level Gradle:
implementation "com.google.dagger:hilt-android:2.35.1"
kapt "com.google.dagger:hilt-android-compiler:2.35.1"
in Project Level Gradle:
classpath "com.google.dagger:hilt-android-gradle-plugin:2.35.1"
Happy Coding!!

Cannot access 'androidx.activity.result.ActivityResultCaller'

I'm using androidx for quite a while and my Android project compiles fine, however recently my Android Studio throws tons of red for all Activity classes
because of
cannot access 'androidx.activity.result.ActivityResultCaller' which is a supertype of ...
I use
AppCompatActivity from androidx.appcompat:appcompat:1.1.0
My build.gradle has:
ext.kotlin_version = '1.3.71'
...
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
classpath 'com.google.gms:google-services:4.3.3'
And gradle version
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
My gradle.properties:
android.useAndroidX=true
android.enableJetifier=true
org.gradle.jvmargs=-Xmx4608m
org.gradle.parallel=true
# Use kapt in parallel
kapt.use.worker.api=true
# Kapt compile avoidance
kapt.include.compile.classpath=false
This happened because of Gradle when resolving dependency libraries versions upgraded androidx.core:core to version more than 1.2.0, probably to 1.3.0-beta01 or 1.3.0-rc01
AppCompatActivity extends FragmentActivity
that extends ComponentActivity
that extends androidx.core.app.ComponentActivity
that implements ActivityResultCaller
introduced in androidx.activity:activity:1.2.0-alpha03 only.
To resolve this issue add this dependency to your module build.gradle:
dependencies {
implementation "androidx.activity:activity-ktx:1.2.0-alpha03"
}
In my case, turns out I had conflicting androidx.activity:activity-ktx gradle dependencies between my core/base and app module.
In addition to ActivityResultCaller, mine was throwing an issue with ActivityResultRegistryOwner.
For me, removing the dependency from the app module, pushing the core module dependency to androidx.activity:activity-ktx:1.2.0-alpha04 and bumping implementation "androidx.core:core-ktx:1.3.0 > 1.3.1 solved both issues.
I also have an androidx.appcompat:appcompat:1.3.0-alpha01 dependency in core, which I kept, but it seems removing it has no effect.
In my case, I needed to remove implementation 'androidx.appcompat:appcompat:1.3.0-alpha01' while keeping implementation "androidx.core:core-ktx:1.3.1"

Mockito is not recognized by Android (Kotlin)

Here is my class test:
private const val FAKE_STRING = "APP NAME"
#RunWith(MockitoJUnitRunner::class)
class UnitTestSample {
#Mock
private lateinit var mockContext: Context
#Test
fun readStringFromContext_LocalizedString() {
// Given a mocked Context injected into the object under test...
`when`(mockContext.getString(R.string.app_name))
.thenReturn(FAKE_STRING)
val myObjectUnderTest = ClassUnderTest(mockContext)
// ...when the string is returned from the object under test...
val result: String = myObjectUnderTest.getHelloWorldString()
// ...then the result should be the expected one.
assertThat(result, `is`(FAKE_STRING))
}
}
Here is a piece of my gradle.build.kt (Kotlin DSL):
plugins {
id("com.android.application")
kotlin("android")
kotlin("kapt")
kotlin("android.extensions")
id("com.onesignal.androidsdk.onesignal-gradle-plugin")
jacoco
maven
}
dependencies {
...
//Test base
testImplementation("junit:junit:4.12")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.0.3")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.0.3")
androidTestImplementation("androidx.test:runner:1.2.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.2.0")
//Unit Tests
testImplementation("org.mockito:mockito-core:3.0.0")
testImplementation("org.mockito:mockito-inline:3.0.0") //support for kotlin final classes
//Android UI Test
androidTestImplementation("org.robolectric:robolectric:3.7.1")
}
As you can see, Android Studio doesn't reognize Mockito. I've already imported org.mockito.junit.MockitoJUnitRunner
I'm running this sample unit test under
src/test/java/.../UnitTestSample.kt
Do you have any idea on how to make it work?
Edit (Solution):
I finally made it work with some help of the comments section. The problem was caused by "maven" plugin import on plugins section, and I didn't see that because the base project I downloaded to convert my Gradle to DSL Kotlin had those plugins working. Somehow this was causing Mockito not to be available at compile time, as #MartinZeitler stated. According to #second, "Maven's runtime does not translate to gradle's runtimeOnly but instead compile".
The error message is pretty clear: an annotation argument must be a compile time argument.
Replace testImplementation with:
debugImplementation "org.mockito:mockito-android:3.2.4"
debugImplementation "org.mockito:mockito-inline:3.2.4"
Edit: Cleaned up the answer
For JUnit5 and mockito use the following dependencies (or newer) and scopes:
testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
compile("org.junit.jupiter:junit-jupiter-engine:5.4.2")
testImplementation("org.mockito:mockito-core:3.0.0")
testImplementation("org.mockito:mockito-junit-jupiter:3.0.0")
testImplementation("org.mockito:mockito-inline:3.0.0")
In your test use the Extension instead of the Runner (which is for JUnit 4).
#ExtendWith(MockitoExtension::class)
When running with the JUnit 5 dependencies of 5.0.3, I got the following error, so consider upgrading to a newer version (as shown in the dependencies above).
java.lang.NoSuchMethodError:
org.junit.platform.commons.support.AnnotationSupport.findAnnotation(Ljava/util/Optional;Ljava/lang/Class;)Ljava/util/Optional;
...
Suppressed: java.lang.NullPointerException
at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:214)
For the maven to gradle conversion I used this site
https://sagioto.github.io/maven2gradle/

Kotlin Unit Test Not Finding Module Dependency Interface

I have an app module and a domain module. In my domain module I have an interface called Repository. In my app module I use dagger to inject an implementation for this into my class and this works fine.
When I then go to test it using a kotlin unit test, at runtime I get a NoClassDefFoundError.
I have also tried to include the domain module in my app modules dependencies like so but that also did not work:
testImplementation project(':domain')
Here are my current test dependencies and also how I'm including the module
implementation project(':domain')
testImplementation 'junit:junit:4.12'
testImplementation 'com.nhaarman:mockito-kotlin:1.5.0'
In my unit test I'm using it like this which could be the issue:
#Mock lateinit var mockRepo : Repository
Thanks to #Mark Keen, I was able to find a reported bug on the Jetbrains site.
This contained a solution from a user called #Calin. Adding the following to the projects's build.gradle file and triggering a gradle sync does the trick.
subprojects { subProject ->
afterEvaluate {
if (subProject.plugins.hasPlugin("kotlin") && subProject.plugins.hasPlugin("java-library")) {
subProject.kotlin.copyClassesToJavaOutput = true
subProject.jar.duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
}

Categories

Resources