会议室数据库类的初始化

时间:2019-10-11 11:22:15

标签: android kotlin android-room

val db = Room.databaseBuilder(
        applicationContext,
        AppDatabase::class.java, "database-name"
    ).build()

是否必须在mainactivity中使用aboove代码创建数据库类的实例?在Android ROOM中?

1 个答案:

答案 0 :(得分:0)

您可以拥有单例数据库类,并在整个应用程序中直接使用它。无需一次又一次地创建其实例。

只要需要DB Object,只需像下面一样使用

  db = AppDatabase.getInstance(activity.applicationContext)

单班

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(
    entities = [Abc::class],
    version = 1,
    exportSchema = false
)

@TypeConverters(CustomTypeConvertes::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun abcDao(): AbcDao

    companion object {

        private var INSTANCE: AppDatabase? = null

        private val lock = Any()

        fun getInstance(context: Context): AppDatabase {
            synchronized(lock) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(
                        context.applicationContext,
                        AppDatabase::class.java, "database-name"
                    ).addCallback(object : RoomDatabase.Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            Console.debug("database-name", "Database created")
                            super.onCreate(db)
                        }

                        override fun onOpen(db: SupportSQLiteDatabase) {
                            Console.debug("database-name", "Database opened")
                            super.onOpen(db)
                        }
                    })
                        .fallbackToDestructiveMigration()
                        .build()
                }
                return INSTANCE!!
            }
        }
    }

}