Подтвердить что ты не робот

Номер не может найти реализацию

У меня проблема с тестированием базы данных Room: когда я запускаю тест, я получаю это исключение:

java.lang.RuntimeException: cannot find implementation for database.TicketDatabase. TicketDatabase_Impl does not exist
at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:92)
at android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:454)
at com.sw.ing.gestionescontrini.DatabaseTest.setDatabase(DatabaseTest.java:36)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1886)

Класс DatabaseTest:

public class DatabaseTest {

    TicketDatabase database;
    DAO ticketDAO;


    @Before
    public void setDatabase() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Context context = InstrumentationRegistry.getTargetContext();
        database = Room.inMemoryDatabaseBuilder(context, TicketDatabase.class).build();

        Method method = TicketDatabase.class.getDeclaredMethod("ticketDao()");
        method.setAccessible(true);
        ticketDAO = (DAO) method.invoke(database, null);
    }
}

gradle файл:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.sw.ing.gestionescontrini"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    defaultConfig {
        multiDexEnabled true
    }
    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:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'
    compile 'android.arch.persistence.room:rxjava2:1.0.0-rc1'
    testCompile'android.arch.persistence.room:testing:1.0.0-rc1'

}

Я не знаю, какова должна быть эта реализация, я искал решение, но все, что я нашел, не работает для меня. Например, многие нашли решение, добавляющее kapt "android.arch.persistence.room...", но gradle не распознает "kapt".

4b9b3361

Ответ 1

kapt для Котлина.

Сначала добавьте:

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

на закрытие dependencies.

Затем обновите android.arch.persistence.room:rxjava2 и android.arch.persistence.room:testing до 1.0.0 вместо 1.0.0-rc1.

ссылка: https://developer.android.com/jetpack/androidx/releases/room

Ответ 2

для Kotlin измените ключевое слово annotationProcessor на kapt в файле Gradle.

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

а также добавить поверх файла зависимостей

apply plugin: 'kotlin-kapt'

ссылка: https://developer.android.com/jetpack/androidx/releases/room

Ответ 3

Если вы используете Kotlin, этот код обязательно присутствует в вашем файле оценок.

apply plugin: "kotlin-kapt"

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

Документация: https://developer.android.com/jetpack/androidx/releases/room

Ответ 4

Я вижу, что некоторые люди здесь (Vishu Bhardwaj и другие по аналогичным вопросам StackOverflow) жалуются, что принятый ответ им не подходит. Я думаю, что заслуживает упоминания, что у меня была аналогичная проблема в проекте MULTI modules, который нуждался в трюке вокруг принятого ответа.

В моих проектах с несколькими модулями зависят зависимости базы данных комнаты, в которых в основном используется один базовый модуль и экспортируется с использованием правильной записи api, но код комнаты был разделен на два разных модуля. Проект скомпилирован без предупреждения, но java.lang.RuntimeException: не удается найти реализацию для базы данных... был поднят во время выполнения.

Это было исправлено добавлением

annotationProcessor "android.arch.persistence.room:compiler:$room_version"

в ВСЕХ модулях, которые включают код, связанный с комнатой.

Ответ 5

Этот град отлично работает. Обратите внимание на плагин kotlin-kapt в начале. Это важно.

apply plugin: 'kotlin-kapt'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "????"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'android.arch.persistence.room:runtime:1.1.1'
    kapt 'android.arch.persistence.room:compiler:1.1.1'
}

Ответ 6

Я сделал, как все говорили в ответе выше, все еще не повезло.
Проблема с моей стороны заключалась в том, что я делал вставку в основной поток.

roomDatabase = Room.databaseBuilder(DexApplication.getInstance(),MyRoomDatabase.class,"db_name")
                    .fallbackToDestructiveMigration() // this is only for testing, 
                       //migration will be added for release
                    .allowMainThreadQueries() // this solved the issue but remember that its For testing purpose only
                    .build();

Объяснение:

.allowMainThreadQueries() 

позволяет выполнять запросы в основном потоке. Но имейте в виду, чтобы удалить его и внедрить RxJava, Live Data или любой другой механизм фоновых процессов для запросов к базе данных. Надеюсь, это поможет.

Ответ 7

Добавьте ниже плагин и зависимость

применить плагин: 'kotlin-kapt'

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

Ответ 8

You can see your database tables on DB browser for SQLITE.

 In android studio 
1. Click on View -> Tool Windows -> Device File Explorer -> data
2. Select your project package name -> database -> select all file and save on desktop

Install **DB browser for SQLITE** 
1. sudo apt-get install sqlitebrowser //write on your terminal for install DB browser
2. install DB browser for sqlite
3. click on Open database and select file where you had saved your data
4. click on Brower Data and see your tables

This is all where i have see my android room database

Ответ 9

Я добавлю полный ответ, который решил мою проблему

Сначала добавьте все зависимости комнаты от Android X второй добавить применить плагин: 'kotlin-kapt' и заменить аннотацию процессора комнаты компилятор с сохраненным