0

I get the following error when using the following custom application class, the class only initialises a Room Database instance to be used throughout the application:

class MyApplication : Application() {
    var appDB: AppDatabase = Room.databaseBuilder(
        applicationContext, AppDatabase::class.java, "Sensor App Database"
    ).build()
}
    java.lang.RuntimeException: Unable to instantiate application com.example.test.MyApplication: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

The application builds normally when I remove the custom application class from the android manifest:

<application
        android:name=".MyApplication"
  • Your variable `appDB` is initialized with the `MyApplication` class, but `applicationContext` is not available at that time : you have to wait until `attachBaseContext()` is called by the system. You might want declare `appDB` as `lateinit var` and initialize it in the `onCreate()` method instead (where `applicationContext` is available). Note that you can also use `this` instead of `applicationContext` because you already are in the application class. See [Application lifecycle]() for more information. – tonymanou Feb 07 '22 at 16:02
  • 1
    I think this is a good candidate for a ``lazy`` delegate, i.e. ``var appDB: AppDatabase by lazy { Room.databaseBuilder( ... ).build() }`` - like @tonymanou says, there is no ``applicationContext`` when the ``Application`` is being constructed, but if it's wrapped in a ``lazy`` and it's not accessed until there *is* an ``applicationContext``, it'll work fine – cactustictacs Feb 07 '22 at 18:17

0 Answers0