Android Room + Kotlin模式

时间:2017-06-17 20:11:01

标签: kotlin android-room

Android Room文档说我们应该在实例化AppDatabase对象时遵循单例设计模式。

我正在考虑它,我想知道它是否建议将AppDatabase类放在我的Application类中。或者,如果我可以使用Kotlin单身人士。

假设我有一个名为CarroDAO的DAO和一个RoomRatabase类CarrosDatabase。

使用Kotlin对象/单例创建DatabaseManager类是否可以?

object DatabaseManager {
    private var dbInstance: CarrosDatabase

    init {
        val appContext = MyApplication.getInstance().applicationContext

        dbInstance = Room.databaseBuilder(
                appContext,
                CarrosDatabase::class.java,
                "mybd.sqlite")
                .build()
    }

    fun getCarroDAO(): CarroDAO {
        return dbInstance.carroDAO()
    }
}

所以我可以像这样得到DAO类:

val dao = DatabaseManager.getCarroDAO()

1 个答案:

答案 0 :(得分:0)

根据Android文档,我们可以使用单例设计模式创建数据库实例,如下所示 创建一个会议室数据库实体

@Entity
data class User(
    @PrimaryKey var uid: Int,
    @ColumnInfo(name = "first_name") var firstName: String?,
    @ColumnInfo(name = "last_name") var lastName: String?
)

创建DAO类

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<User>

    @Query("SELECT * FROM user WHERE first_name LIKE:  first AND " +
           "last_name LIKE :last LIMIT 1")
    fun findByName(first: String, last: String): User

    @Insert
    fun insertAll(vararg users: User)

    @Delete
    fun delete(user: User)
}

使用单例模式创建数据库

@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        @Volatile
        private var instance: AppDatabase? = null

        fun getInstance(
            context: Context
        ): AppDatabase = instance ?: synchronized(this) {
            instance ?: buildDatabase(context).also { instance = it }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(
                context,
                AppDatabase::class.java,
                "database-name"
            ).build()
        }
    }
}

您可以通过以下代码获取数据库实例

 var databaseInstance=AppDatabase.getInstance(context)