我想使用我的函数getDatabase(context)
在Kotlin中构建房间,但我遇到了这个错误:
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)
这很奇怪,因为这是我第一次遇到这个错误(我在其他项目中使用Room并没有出现这个错误)。 应用程序不会崩溃,但数据库无法正常工作。
我尝试在互联网上查找,但我没有看到与这个错误相关的任何信息(只有这位日本人:https://teratail.com/questions/118177,但我不懂日语)。 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
}
这是我的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'
}
getDatabase
方法? - Michał Baran