Null object reference when I try to build room

2019-07-03 00:35发布

问题:

I want to build room in Kotlin using my function getDatabase(context) and I have this error :

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Package.getName()' on a null object reference
W/System.err:     at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:77)

This is very strange because it's the first time I have this error (I use Room in other project and I don't have this bug). The app don't crash but the database is not working.

I try looking in internet but I don't see nothing about this bug (only this japanese guy : https://teratail.com/questions/118177 but I don't understand japanese).

AppDatabase :

@Database(entities = [(Wallet::class), (Historique::class)], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun walletDao(): WalletDao
    abstract fun historiqueDao(): HistoriqueDao
}

private var INSTANCE: AppDatabase? = null

fun getDatabase(context: Context?): AppDatabase {
    if (INSTANCE == null)
        INSTANCE = context?.let { Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME).build() }
    return INSTANCE as AppDatabase
}

This is my Gradle :

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

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "my.app"
        minSdkVersion 19
        targetSdkVersion 27
        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-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:support-v4:27.1.1'

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

    implementation "org.jetbrains.anko:anko-commons:0.10.4"
    implementation "org.jetbrains.anko:anko-design:0.10.4"
    implementation "com.chibatching.kotpref:kotpref:2.5.0"
    implementation "com.chibatching.kotpref:initializer:2.5.0"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

回答1:

The problem was from some imports (by coping the class from an other project).