I am a neophite in Kotlin. I need to call a method in a class created in Kotlin from a Java class. The class in question concerns the creation of the db.
@Database(entities = arrayOf(Indirizzo::class, Dispositivo::class), version = 1, exportSchema = false)
abstract class WppDb : RoomDatabase() {
    abstract fun DispositivoDao(): DispositivoDao
    abstract fun IndirizzoDao(): IndirizzoDao
    private var INSTANCE : WppDb? = null
    fun getInstance(context: Context): WppDb? {
        if (INSTANCE == null) {
            synchronized(WppDb::class) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WppDb::class.java, "weather.db")
                           .build()
            }
        }
        return INSTANCE
    }
    fun destroyInstance() {
        INSTANCE = null
    }
}
I need to call the getInstance() method from a Java Activity.
If you want the equivalent of what Room samples usually show with a static Java field and static getter method for it, you can place those functions in the companion object of your class:
@Database(entities = arrayOf(Indirizzo::class, Dispositivo::class), version = 1, exportSchema = false)
abstract class WppDb : RoomDatabase() {
    abstract fun DispositivoDao(): DispositivoDao
    abstract fun IndirizzoDao() : IndirizzoDao
    companion object {
        private var INSTANCE : WppDb? =  null
        @JvmStatic
        fun getInstance(context: Context): WppDb? {
            if (INSTANCE == null) {
                synchronized(WppDb::class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                    WppDb::class.java, "weather.db")
                                   .build()
                }
            }
            return INSTANCE
        }
        @JvmStatic
        fun destroyInstance() {
            INSTANCE = null
        }
    }
}
You can then call WppDb.getInstance(context) from either Kotlin or Java code. Note the @JvmStatic annotations which make these calls nicer in Java - without them, you'd have to use WppDb.Companion to get the companion object, and then call the getInstance function on that (so WppDb.Companion.getInstance(context) altogether).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With