Unresolved reference: HiltTestApplication error - android

I'm trying to create a HiltTestRunner class for testing with Hilt. Here is the code:
package com.example.newsworld.application
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
class HiltTestRunner : AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
The problem is that for HiltTestApplication it shows an error saying Unresolved reference: HiltTestApplication. Then in Show Context Options it gives me an option to Add library 'Gradle: com.google.dagger:hilt-android-testing:2.44#arr' to classpath, but nothing happens if I click on it. I've added the following dependencies:
implementation("com.google.dagger:hilt-android:2.44")
kapt("com.google.dagger:hilt-android-compiler:2.44")
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.44'
kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.44'
Project level build.gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.5.31'
}
plugins {
id 'com.android.application' version '7.4.1' apply false
id 'com.android.library' version '7.4.1' apply false
id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
id 'com.google.dagger.hilt.android' version "2.44" apply false
}
ext {
activityVersion = '1.4.0'
appCompatVersion = '1.4.0'
constraintLayoutVersion = '2.1.2'
coreTestingVersion = '2.1.0'
coroutines = '1.5.2'
lifecycleVersion = '2.5.1'
materialVersion = '1.4.0'
roomVersion = '2.5.0'
// testing
junitVersion = '4.13.2'
espressoVersion = '3.4.0'
androidxJunitVersion = '1.1.3'
}
App level build.gradle file plugins:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id("kotlin-parcelize")
id 'org.jetbrains.kotlin.android'
id("com.google.dagger.hilt.android")
}

Related

implementing hilt in android with kapt Execution failed for task ':app:kaptDebugKotlin'

I have been using hilt in my several android projects. But since I have updated my android studio to latest version Chipmunk// 2021.2.1, this error comes every time when I just build project
Execution failed for task ':app:kaptDebugKotlin'.
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
java.lang.reflect.InvocationTargetException (no error message)
I am checking it on sample app which is just just one dependency injection, using hilt and kapt.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
allprojects {
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
dependencies {
// Hilt Classpath for Java
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'
}
}
plugins {
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
apply plugin: 'com.android.application'
apply plugin: 'org.jetbrains.kotlin.android'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
android {
compileSdk 32
defaultConfig {
applicationId "com.example.hiltkotlinpractice"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation("com.google.dagger:hilt-android:2.38.1")
kapt("com.google.dagger:hilt-android-compiler:2.38.1")
kapt 'androidx.hilt:hilt-compiler:1.0.0'
}
#HiltAndroidApp
class App: Application()
#Module
#InstallIn(ActivityComponent::class)
class AppModule {
#Provides
fun provideInterface(): APIProvider {
return APIProvider()
}
}
class Repo #Inject constructor(
val apiProvider: APIProvider
) {
fun get() = apiProvider.getData()
}
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val repo = Repo(APIProvider())
Log.d(TAG, repo.get())
}
}
Try using "annotationProcessor" instead of the "kapt" in the build.gradle dependencies. Worked for me.

Starting out with Room, encountered this error: incompatible types: NonExistentClass cannot be converted to Annotation

I have looked at the solutions presented at each of these links.
NonExistentClass cannot be converted to Annotation - app:kaptDebugAndroidTestKotlin
-- Not relevant as I am not using JUnit5.
error: incompatible types: NonExistentClass cannot be converted to Annotation #error.NonExistentClass()
-- Two issues, one is I don't know where to put kapt { } and I tried leaving it as a global, but that didn't do anything and putting it in dependency caused a error.
NonExistentClass cannot be converted to Annotation
-- Unsure where to set generateStubs to true and where to set correctErrorTypes to true in my build.gradle file. I don't know if I can use annotationProcessor on it's own.
On my own I tried to implement android.arch before realizing it is deprecated.
I tried to use ksp but that returned an error stating that the complier doesn't know where the ksp() method is. Using
implementation("com.google.devtools.ksp:symbol-processing-api:1.5.0-1.0.0-alpha10")
did not resolve the error with ksp.
The error message exactly: "error: incompatible types: NonExistentClass cannot be converted to Annotation"
#error.NonExistentClass()
Here is my module build.gradle
plugins {
id 'com.android.application'
// id 'com.android.feature'
id 'kotlin-android'
id 'kotlin-kapt'
//id 'dagger.hilt.android.plugin'
//id 'kotlin-ksp'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
//apply plugin: 'dagger.hilt.android.plugin'
//apply plugin: 'com.android.feature'
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.testingdatabases"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
kapt {
correctErrorTypes = true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
// ROOM - -- - --- - - - >
def room_version = "2.3.0"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor "androidx.room:room-compiler:$room_version"
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$room_version")
// To use Kotlin Symbolic Processing (KSP)
// ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
api("io.grpc:grpc-kotlin-stub:1.0.0")
// implementation("com.google.devtools.ksp:symbol-processing-api:1.5.0-1.0.0-alpha10")
// < -- - - - End of Room stuff
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Here is the project's build.gradle file,
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
def nav_version = "2.3.0-alpha01"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Here is the applications code,
package com.example.testingdatabases
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.room.RoomDatabase;
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
#Entity
data class User(
#PrimaryKey val uid: Int,
#ColumnInfo(name = "first_name") val firstName: String?,
#ColumnInfo(name = "last_name") val lastName: String?
)
#Dao
interface UserDao {
#Query("SELECT * FROM user")
fun getAll(): List<User>
#Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<User>
#Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
#Insert
fun insertAll(vararg users: User)
#Delete
fun delete(user: User)
}
#Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
in gradle implementation "a-b-x" is used and in kotlin dsl implemntation("a-b-x") is used ,don't mix
Your database is not build properly (According to me) Here

Gradle Error: 'Cannot change dependencies of configuration ':app:api' after it has been included in dependency resolution.' [duplicate]

I am trying to get Realm to work in my project. I have Kotlin with version 1.2.51 and Instant Run disabled.
In my project build.gradle file I added the following dependency:
classpath "io.realm:realm-gradle-plugin:5.4.0"
In my App build.gradle file I applied the Realm plugin as explained in the tutorial:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'
When I am trying to build the project, I get the following error:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'
Caused by: org.gradle.api.InvalidUserDataException: Cannot change dependencies of configuration ':app:api' after it has been included in dependency resolution.
When I change the order of apply plugin so that realm is directly after com.android.application the project builds.
The problem then is, that Realm tells me on my first insert of a RealmObject, that the object is not contained in the object scheme.
RealmCustomer.kt
open class RealmCustomer(
#PrimaryKey
var id: String = "",
var firstname: String = "",
var lastname: String = "",
var addresses: RealmList<RealmAddress> = RealmList()
) : RealmObject() {}
RealmAddress.kt
open class RealmAddress(
var street: String = "",
var streetNr: String = "",
var city: String = "",
var countryCode: String = ""
) : RealmObject() {}
As far as I can see, there should not be a problem with it.
In my Applications onCreate I call the following code:
Realm.init(this)
RealmConfiguration.Builder().name("my.realm").build().apply { Realm.setDefaultConfiguration(this) }
At some point later, I retrieve my Realm like this:
private val realm: Realm by lazy { Realm.getDefaultInstance() }
fun save(items: List<...>) {
realm.executeTransaction {
items.map {
val addressList = it.addresses?.map {
realm.createObject(RealmAddress::class.java).apply {
street = it.street
streetNr = it.streetNr
city = it.city
countryCode = it.countryCode
}
}
val cx = realm.createObject(RealmCustomer::class.java, it.id).apply {
firstname = it.firstname
lastname = it.lastname
}
addressList?.forEach { cx.addresses.add(it) }
}
}
}
This code with apply plugin: 'realm-android' in the second place crashed with the Schema error: RealmException: RealmAddress is not part of the schema for this Realm
Thank you in advance.
Seems to be a bug in the Realm-Transformer 5.4.0, which happens only if experimental = true is enabled for Kotlin Android Extensions.
EDIT: Using 5.4.1+ should solve this problem.
PREVIOUS ANSWER: You can use manually defined versions in the build.gradle file in the meantime:
buildscript {
ext.kotlin_version = '1.2.51'
ext.realm_version = '5.4.0'
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "io.realm:realm-transformer:5.1.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
import io.realm.transformer.RealmTransformer
android.registerTransform(new RealmTransformer(project))
dependencies {
implementation "io.realm:realm-annotations:$realm_version"
implementation "io.realm:realm-android-library:$realm_version"
implementation "io.realm:realm-android-kotlin-extensions:$realm_version" {
exclude group: "org.jetbrains.kotlin", module: "kotlin-stdlib-jdk7"
}
kapt "io.realm:realm-annotations-processor:$realm_version"
}
As per docs.

Could not find class databinding.FragmentBinding

I'm trying to use databinding in my fragment but I get the following error on runtime:
Could not find class 'com.example.databinding.FragmentUpSellBinding', referenced from method com.example.UpSellFragment.onCreateView
Which results into:
FATAL EXCEPTION: main Process: nl.anwb.fietsen.debug, PID: 5563
java.lang.IllegalStateException: DataBindingUtil.inflate(…r,
false) must not be null`
my build.gradle looks like this:
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
dataBinding {
enabled = true
}
}
kapt {
generateStubs = true
}
dependencies {
kapt 'com.android.databinding:compiler:3.0.0-alpha4'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
Main buid.gradle
buildscript {
ext.kotlin_version = '1.1.2-4'
ext{
supportLibraryVersion = '25.3.1'
}
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
Does anyone know how I can fix this?
build.gradle in you don't need
dataBinding {
enabled = true
}
Remove and try
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
kapt {
generateStubs = true
}
dependencies {
kapt 'com.android.databinding:compiler:3.0.0-alpha4'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
And update your Kotlin to
ext.kotlin_version = '1.1.3-2'
Sanne, I have the exact same build.gradle files as you, except for a newer gradle -alpha9 and don't get the runtime error from onCreateView when using DataBindingUtil.inflate(inflater,...).
In my case dataBinding { enabled = true } is required.
However I did get a build error (Unresolved reference: databinding) when using FragmentXBinding.inflate(inflater) until I specified FragmentXBinding.inflate(inflater as LayoutInflater).

Android Library, Kotlin and Dagger2

I'm building an application that have two modules: the Core module, that is an Android Library (com.android.library) and the Application module (com.android.application).
After I converted the Java files to Kotlin, the project is not compiling, giving me an error that the generated Dagger 2 files were not found (unresolved reference). But those files currently being generated under:
...core\build\generated\source\kapt\release{my\core\namespace}\DaggerBaseComponent.java
What I'm missing?
build.gradle (Core module)
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
...
android {
...
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
...
// Dagger.
kapt "com.google.dagger:dagger-compiler:2.10"
compile 'com.google.dagger:dagger:2.10'
provided 'javax.annotation:jsr250-api:1.0'
// Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
build.gradle (Application module)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
...
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
...
// Dagger.
kapt "com.google.dagger:dagger-compiler:2.10"
compile 'com.google.dagger:dagger:2.10'
provided 'javax.annotation:jsr250-api:1.0'
// Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
build.gradle (Project)
buildscript {
ext.kotlin_version = '1.1.2-3'
...
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
ApplicationContext.kt (of my Core Module)
class ApplicationContext : Application() {
var baseComponent: BaseComponent? = null
private set
override fun onCreate() {
super.onCreate()
initializeInjector()
}
private fun initializeInjector() {
// DaggerBaseComponent is and unresolved reference
baseComponent = DaggerBaseComponent.builder()
.appModule(AppModule(this))
.endpointModule(EndpointModule())
.build()
}
companion object {
operator fun get(context: Context): ApplicationContext {
return context.applicationContext as ApplicationContext
}
}
}
The problem was that Gradle was not finding the Dagger generated files by kapt, so I solved the problem by adding src/main/kapt to my sourceSets configuration on my Core module (lib):
build.gradle (Core module)
android {
...
sourceSets {
main.java.srcDirs += ['src/main/kotlin', 'src/main/kapt']
}
}
After that, the Core module started finding their Dagger 2 generated files.
Java module should have
plugins {
id("java-library")
id("kotlin")
id("kotlin-kapt")
}
java {
sourceSets {
main.java.srcDirs += ['build/generated/source/kapt/main']
}
}

Categories

Resources