我想到了以下问题:

我的MainActivity代码:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...
        // ERROR: Cannot create instance of an abstract class
        var db = DataBase().getDataBase(this)
        // ...
    }
}

session 室数据库:
@Database(entities = arrayOf(DataBaseUser::class), version = 1)
abstract class DataBase : RoomDatabase() {

    val DB_NAME : String = "DataBaseUser"
    private lateinit var INSTANCE : DataBase

    fun getDataBase(context: Context): DataBase {
        if (INSTANCE == null){
            INSTANCE = Room.databaseBuilder(context.applicationContext,DataBase::class.java,DB_NAME).build()
        }
        return INSTANCE
    }

    abstract fun getUserDao(): DataBaseUserDao
}

我无法在Kotlin上实例化该类。在Java中,我这样做是这样的:
db = AppDataBase.getDataBase(view.getContext());

如何在Kotlin中获得相同的结果?

最佳答案

使用单例(在Kotlin object中)保存Room数据库实例:

@Database(entities = arrayOf(DataBaseUser::class), version = 1)
abstract class DataBase : RoomDatabase() {
    abstract fun getUserDao(): DataBaseUserDao
}

object DatabaseProvider {
    val DB_NAME : String = "DataBaseUser"
    private lateinit var INSTANCE : DataBase

    fun getDataBase(context: Context): DataBase {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.applicationContext,DataBase::class.java,DB_NAME).build()
        }

        return INSTANCE
    }
}

用法:
val db = DatabaseProvider.getDataBase(view.getContext())

07-26 06:25