256

My app database class

@Database(entities = {Detail.class}, version = Constant.DATABASE_VERSION)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract FavoritesDao favoritesDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build();

                    //Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

Gradle lib:

 compile "android.arch.persistence.room:runtime:+"   
 annotationProcessor "android.arch.persistence.room:compiler:+"

And when i ask for instance it will give this error, AppDatabase_Impl does not exist in my application class

public class APp extends Application {

    private boolean appRunning = false;

    @Override
    public void onCreate() {
        super.onCreate();
        AppDatabase.getAppDatabase(this); //--AppDatabase_Impl does not exist

    }   

}
Radesh
  • 13,084
  • 4
  • 51
  • 64
pratik deshai
  • 2,770
  • 2
  • 11
  • 13

32 Answers32

539

For those working with Kotlin, try changing annotationProcessor to kapt in the apps build.gradle

for example:

// Extensions = ViewModel + LiveData
implementation "android.arch.lifecycle:extensions:1.1.0"
kapt "android.arch.lifecycle:compiler:1.1.0"
// Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"

also remember to add this plugin

apply plugin: 'kotlin-kapt'

to the top of the app level build.gradle file and do a clean and rebuild (according to https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#6)

In Android Studio, if you get errors when you paste code or during the build process, select Build >Clean Project. Then select Build > Rebuild Project, and then build again.


UPDATE

If you have migrated to androidx

def room_version = "2.3.0" // check latest version from docs

implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"

UPDATE 2 (since July 2021)

def room_version = "2.3.0" // check latest version from docs

implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
nayriz
  • 353
  • 1
  • 17
RWIL
  • 8,729
  • 1
  • 28
  • 37
  • 2
    Thanks a lot. Just moving to Kotlin and all my test cases started failing. Was banging my head. Then I accidentally saw this comment. Saved my day. – Ozeetee Mar 20 '18 at 02:58
  • 98
    Also need to add `apply plugin: 'kotlin-kapt'` to the top of the app level `build.gradle` file – olfek Jun 06 '18 at 20:12
  • 3
    This saved me....I think Google should work more on showing proper error...I had kapt call but I didnt add apply kapt-plugin – anoop4real Dec 24 '18 at 10:51
  • Was stuck since yesterday. thanks a lot. I don't understand why don't google people mention this in the documentation. – Shubham Anand Sep 21 '19 at 12:08
  • You're the GOAT saved me with that quick gradle fix – Tonnie Nov 19 '19 at 04:27
  • Works for me but I'd love to understand why, could you elaborate? – Daniel Jan 12 '20 at 17:13
  • 3
    It now has changed to `implementation "androidx.room:room-ktx:$room_version"` – Joe Gasewicz Jul 19 '21 at 17:59
  • FAILURE: Build failed with an exception. * What went wrong: 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) – Chandler Oct 09 '21 at 11:03
  • it worked for me – Ali Salehi Feb 11 '22 at 23:52
94

Just use

apply plugin: 'kotlin-kapt'

in app build.gradle

And keep both in dependencies

annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"
kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"

EDIT

In newer version don't need to add both dependencies at a time Just use, hope it will work.

kapt 'android.arch.persistence.room:compiler:1.1.1'
Jahangir Kabir
  • 1,783
  • 13
  • 17
27

I had this error when I missed

@Database(entity="{<model.class>})

Ensure that the entity model specified in the annotation above refers to the particular model class and also ensure that the necessary annotation:

@Entity(tableName = "<table_name>" ...)

is properly defined and you'd be good

Thadeus Ajayi
  • 993
  • 10
  • 16
  • 2
    For clarity, this goes immediately above the DB class definition. It appears to have fixed my problem - thanks! – winwaed Jun 02 '18 at 02:36
  • make sure you don't have empty constructors (constructor(){}) in your entities https://stackoverflow.com/a/60494924/6148931 – Martynas B Jan 27 '21 at 12:23
  • I had this problem and changing the build.gradle as the accepted answer did not solve the problem. Adding this annotation solved the problem, but in [the tutorial I was following](https://developer.android.com/training/data-storage/room#groovy), the "user" class has only `@Entity`, not `@Entity(tablename="table name" )`. If this is required, why does the tutorial lack this annotation? – Damn Vegetables Dec 26 '21 at 00:29
22

if you are using kotlin classes to implement database then use

apply plugin: 'kotlin-kapt'

and

kapt "android.arch.persistence.room:compiler:1.1.1"

in your gradle file, it will work.

navalkishoreb
  • 533
  • 2
  • 8
  • 16
  • This works on Android Studio 3.5 (however the current room compiler version is 2.1.0) – Yennefer Sep 10 '19 at 16:40
  • 1
    I think most of the people were not using androidx library in whole project... that why I suggested 1.1.1... I myself faced compilation issues and felt safe with minimal changes using older version. – navalkishoreb Sep 11 '19 at 08:53
15

For Kotlin Developers

Use this:

implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"

And add apply plugin: 'kotlin-kapt' to the top of the app level build.gradle.

For Java Developers

implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
Pedro Massango
  • 4,114
  • 2
  • 28
  • 48
13

Agreed with the above answers

The solution is as below. Change annotationProcessor to kapt as below

// annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
Arunabh Das
  • 13,212
  • 21
  • 86
  • 109
12

If you are using kotlin, add kotlin annotation processor plugin to app level build.gradle

plugins {
    id "org.jetbrains.kotlin.kapt"
}

Also remove annotationProcessor and replace it with kapt

  • Instead of
dependencies {
    def room_version = "2.3.0"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
}
  • Use
dependencies {
    def room_version = "2.3.0"
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
}

The annotationProcessor only works in java environment. The kapt takes care of both java and kotlin. If something wrong with your implementation, those plugins will show them at the compile time.

UdaraWanasinghe
  • 2,622
  • 2
  • 21
  • 27
  • tried adding `plugins {...}` and replacing `kapt` with `annotationProcessor` but separately, thank you very much for answering.. – Vivek Thummar Feb 28 '23 at 09:24
11

It is not just about updating your dependencies. Make sure all your Room dependencies have the same version.

implementation 'android.arch.persistence.room:rxjava2:1.1.0-alpha2'
implementation 'android.arch.persistence.room:runtime:1.1.0-alpha2'
annotationProcessor "android.arch.persistence.room:compiler:1.1.0-alpha2"

In the sample snippet above, all my Room dependencies have the same version 1.1.0-alpha2

Idee
  • 1,887
  • 21
  • 31
9

I meet with the problem, because I forget @Dao annotation

@Dao
public interface SearchHistoryDao {
    @Query("SELECT * FROM search_history")
    List<SearchHistory> getAll();

    @Insert
    void insertAll(SearchHistory... histories);

    @Delete()
    void delete(SearchHistory history);
}

Room Official tutorial

duyuanchao
  • 3,863
  • 1
  • 25
  • 16
9

make sure to add correct dependency for room in build.gradle

ext {
   roomVersion = '2.1.0-alpha06'
}

// Room components
implementation "androidx.room:room-runtime:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"

And below line at the top-

apply plugin: 'kotlin-kapt'
Deepak
  • 381
  • 4
  • 3
8

I met this problem because I have forgotten the apt dependences

implementation "android.arch.lifecycle:extensions:$archLifecycleVersion"
implementation "android.arch.persistence.room:runtime:$archRoomVersion"
annotationProcessor "android.arch.lifecycle:compiler:$archLifecycleVersion"
annotationProcessor "android.arch.persistence.room:compiler:$archRoomVersion"

after added the annotationProcessor, and rebuild it, the problem solved.

ahsiu
  • 123
  • 1
  • 6
7

Had the same problem. Implemented the few classes and interface as officially told in a new example project created by Android Studio: https://developer.android.com/training/data-storage/room/

All mentioned solutions above did not help, the necessary _Impl files according to my database class were not generated by Room. Finally executing gradle clean build in terminal gave me the hint that lead to the solution:

"warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide room.schemaLocation annotation processor argument OR set exportSchema to false."

I added the parameter exportSchema = false in the database class

@Database(entities = arrayOf(User::class), version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

And then it worked, found these two generated files in the app module under generatedJava:

  • AppDatabase_Impl
  • UserDao_Impl

I don't understand this behaviour as the parameter is said to be optional, see https://stackoverflow.com/a/44645943/3258117

Hajo
  • 71
  • 1
  • 5
  • 1
    Running ./gradlew clean build from the terminal was the key. For me I got this message: app: 'annotationProcessor' dependencies won't be recognized as kapt annotation processors. Please change the configuration name to 'kapt' for these artifacts: 'android.arch.lifecycle:compiler:1.1.1' and apply the kapt plugin: "apply plugin: 'kotlin-kapt'". – Randy Dec 27 '18 at 08:05
  • Ah yes, executing the tasks in terminal also helped me a lot in the past. The build tools messages in the IDE often "hide" the original error message – Hajo Dec 29 '18 at 14:03
7

The question is pretty old, but I've stumbled on this today and none of the provided answers helped me. Finally I managed to resolve it by noticing that google documentation actually is still adopted to Java and not Kotlin by default, actually they have added a comment which I've ignored

For Kotlin use kapt instead of annotationProcessor

So, instead of

annotationProcessor "androidx.room:room-compiler:$room_version"

If you are developing with Kotlin, you should use:

    kapt "androidx.room:room-compiler:$room_version"
Pavel
  • 1,627
  • 15
  • 12
4

In my kotlin app, I just added the following line at the top of my build.gradle file :

apply plugin: 'kotlin-kapt'

And the following line in the dependencies section:

kapt "androidx.room:room-compiler:2.2.5"

I hope it fixes your issue.

3

Use the following gradle link:

compile 'android.arch.persistence.room:runtime:1.0.0-alpha9'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha9'

You need to create a different singleton class and get the AppDatabase from there like this:

RoomDB.java

public class RoomDB {

private static RoomDB INSTANCE;

public static AppDatabase getInstance(Context context) {
    if (INSTANCE == null) {
        INSTANCE =
                Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build();

                //Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build();
    }
    return INSTANCE;
}

public static void destroyInstance() {
    INSTANCE = null;
}

App.java

public class App extends Application {

private boolean appRunning = false;

@Override
public void onCreate() {
    super.onCreate();
    RoomDB.getInstance(this); //This will provide AppDatabase Instance
}
Amine Karimi
  • 119
  • 12
Burhanuddin Rashid
  • 5,260
  • 6
  • 34
  • 51
3

In my case, I was testing the connectivity for room database and I have put the testing class inside the directory which I have created inside the AndroidTest folder. I have moved it out of the custom directory, then it worked pretty well.

Farruh Habibullaev
  • 2,342
  • 1
  • 26
  • 33
  • This is my issue too. Any idea why this is happening and how to avoid this? I'd rather prefer not to have a `TestDatabase` in the release code. – Eduardo Sep 17 '18 at 13:06
3

The same phenomenon occurred to me.

following

implementation "android.arch.persistence.room:runtime:1.1.1"

Adding causes another build error but tracks the cause from the log.

In my case, there was an error in the SQL implementation. After fixing, the build was successful.

So you may want to check the implementation of the entire room library instead of looking at the crashed locals.

2

The issue is more around the correct library that is not included in the gradle build. I had a similar issue and added the missing

testImplementation "android.arch.persistence.room:testing:$room_version

Saurabh Sharma
  • 155
  • 1
  • 8
2

Changing the dependencies in my gradle file did'nt help me in fixing the error.I had missed this Database annotation in class where Room database was initialized which was causing this issue.

@Database(entities = [UserModel::class], version = 1)

Ensure that the entity model specified in the annotation above refers to the particular model class

2

For me, the Android Studio automatically updated dependencies as soon as you include any of the Room database related imports. But as per https://developer.android.com/jetpack/androidx/releases/room#declaring_dependencies you need to update few. Here is how my code-base looks like:

AppDatabase.kt

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = arrayOf(MyEntity::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun myDAO(): MyDAO

    companion object {
        @Volatile private var instance: AppDatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context)= instance ?: synchronized(LOCK){
            instance ?: buildDatabase(context).also { instance = it}
        }

        private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
            AppDatabase::class.java, "db-name.db")
            .build()
    }
}

Update the build.gradle as specified in one of the answers:

apply plugin: 'kotlin-kapt' // this goes with other declared plugin at top
dependencies { // add/update the following in dependencies section
    implementation 'androidx.room:room-runtime:2.2.3'
//    annotationProcessor 'androidx.room:room-compiler:2.2.3' // remove this and use the following
    kapt "androidx.room:room-compiler:2.2.3"

}

Sync the gradle and you should be good to go.

Rujoota Shah
  • 1,251
  • 16
  • 18
2

For Kotlin Developers


if you checked Dao and Entity and also used Kapt and there is no problem, I guess there is a problem with your kotlin version if you are using kotlin 1.4 and above. update Room to last version from this link.


2.3.0-alpha03 solved my problem.

hamid Mahmoodi
  • 690
  • 4
  • 16
2

Update Answer 2023

I was facing the same issue and after wasting 10 hours and all the above solutions, the following steps worked.

First I changed my gradle version to the latest i.e

distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip

TO

distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip

plus I changed Java version in all modules from

sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8

TO

sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11

After That I did clean and Run but had No Luck, Then I added the following dependencies in my gradle file as per someone's answer.

implementation "androidx.room:room-runtime:2.4.0-alpha01"
annotationProcessor  "androidx.room:room-compiler:2.4.0-alpha01"
kapt  "androidx.room:room-compiler:2.4.0-alpha01"

It didn't work as well but I found suggestion that latest version of room is available for alpha i.e

implementation "androidx.room:room-runtime:2.6.0-alpha01"
annotationProcessor  "androidx.room:room-compiler:2.6.0-alpha01"
kapt  "androidx.room:room-compiler:2.6.0-alpha01"

Now after updating that, it started working!

So I suggest that Update your gradle version, Kotlin version, and Java version and use the latest room it will work. As I am using the multi-module app with Dagger, Many people suggested that add dependencies of Room in the APP Module as well, But I found that there is no need of adding Room in APP Module, Just add it in the core module where required.

Intsab Haider
  • 3,491
  • 3
  • 23
  • 32
2

Here's an answer using ksp. Android developer documentation asserts that kapt is now (May 2023) in maintenance mode. I'm writing a Kotlin app.

Add to your project-level build.gradle:

plugins {
...
   id 'com.google.devtools.ksp' version "1.8.21-1.0.11" apply false
}

Add to your module-level build.gradle:

plugins {
...
   id 'com.google.devtools.ksp'
}
android {
...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
                     // was JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = 11
        // was jvmTarget = '1.8'
    }
    // this may not be necessary but my app has it
    composeOptions {
        kotlinCompilerExtensionVersion '1.4.7'
    }
...
}
kotlin {
    jvmToolchain(11)
}
dependencies {
...
    def room_version = "2.5.1"
    implementation "androidx.room:room-ktx:$room_version"
    ksp "androidx.room:room-compiler:$room_version"
}

In addition, because I was updating the Java version, I got an error about a jlink executable not existing, and solved that by installing the latest JDK on my machine.

Fedora: sudo dnf install java-11-openjdk-devel

Ubuntu: sudo apt install default-jdk default-jre

References:

Google developer documentation on migrating from kapt to ksp: https://developer.android.com/build/migrate-to-ksp

latest ksp release listed here (web search "android latest ksp release"): https://github.com/google/ksp/releases

latest Room release listed here (web search "android latest room release"): https://developer.android.com/jetpack/androidx/releases/room

latest kotlinCompilerExtensionVersion release listed here (web search "android latest kotlinCompilerExtensionVersion release"): https://developer.android.com/jetpack/androidx/releases/compose-compiler

Stack Overflow posts about an error I hit along the way which caused me to update the JDK:

Execution failed for task ':app:kspDebugKotlin'. Unable to build with ksp

'compileDebugJavaWithJavac' task (current target is 1.8) and 'kspDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.

answers found here:

How to set compileJava' task ( 11) and 'compileKotlin' task (1.8) jvm target compatibility to the same Java version in build.gradle.kts?

Build Error: 'kspDebugKotlin' task (current target is 17)

Stack overflow posts about how to fix the error I got ("jlink does not exist") once I'd updated the Java version in build.gradle: How to fix jlink does not exist?

DraftyHat
  • 428
  • 1
  • 2
  • 6
1

In addition to missing

annotationProcessor "android.arch.persistence.room:compiler:x.x.x"

I had also missed adding the below annotation in my class

@Entity(tableName = "mytablename")
Meenohara
  • 314
  • 4
  • 9
1

Nothing works from above answers and I noticed that the issue persists for me when I'm using room version2.3.0 or 2.4.2. However, 2.5.0-alpha01 version works well when I applied it.

build.gradle:app

def roomVersion = '2.5.0-alpha01'
implementation "androidx.room:room-ktx:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"
testImplementation "android.arch.persistence.room:testing:$roomVersion"
zekromWex
  • 280
  • 1
  • 4
  • 17
1

In my case just by changing annotationProcessor to kapt on my room-compiler dependency, did the work.

Rodrigo Salomao
  • 143
  • 1
  • 10
1

As of Jan 2023 - I faced a similar issue after refactoring my code to use ServiceLocator class.

I resolved it by going on a spree of changing room versions. It worked with 2.5.0-alpha02

version_room = "2.5.0-alpha02" <-- build.gradle (project)

 //Room
implementation "androidx.room:room-runtime:$version_room"
kapt "androidx.room:room-compiler:$version_room"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$version_room"
implementation("androidx.room:room-guava:$version_room")

I am running the following on Android Eel 2020.1.1:

version_kotlin = "1.7.21" version_android_gradle_plugin = "4.0.1"

awaqar
  • 149
  • 1
  • 6
1

Following are the dependencies I have used to resolve this issue :

plugins {
    id 'kotlin-kapt'
}

dependencies {
    //dependencies for room
     implementation("androidx.room:room-runtime:2.5.1")
     kapt "androidx.room:room-compiler:2.5.1"
     kapt "android.arch.persistence.room:compiler:1.1.1"
}
Mudit Goel
  • 196
  • 1
  • 5
0

Reading the example here: Room Example

I fixed this error just using the correct (I guess it is) annotationProcessorFile, as follows:

annotationProcessor "android.arch.persistence.room:compiler:<latest_version>"

Also, I upgraded to 2.2.0 either in Room Version as in Lifecycle version.

Once synchronized the graddle, I could start working with Room.

So, Good luck! And let the code be with you!

Anibal Itriago
  • 1,051
  • 10
  • 13
0

Not in the case of OP, but this also happens when you mistakenly use implementation instead of annotationProcessor like this:

implementation "android.arch.persistence.room:compiler:x.x.x"

Instead of this:

annotationProcessor "android.arch.persistence.room:compiler:x.x.x"
artenson.art98
  • 1,543
  • 15
  • 15
0

Just in case anyone out there should make the same mistake as I did, don't call your database class "Database" or you'll get the same error.

0

check this annotation above class

@Database(entities = arrayOf(Schedule::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
// ....
}