Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Kotlin function in Java

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.

like image 928
Anto Avatar asked Jul 03 '18 15:07

Anto


1 Answers

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).

like image 60
zsmb13 Avatar answered Oct 04 '22 06:10

zsmb13