美文网首页
Kotlin + Room + LiveData监听数据库数据变

Kotlin + Room + LiveData监听数据库数据变

作者: Obadiah | 来源:发表于2020-07-10 20:11 被阅读0次

    搞了一天终于搞出来了……一直不成功好像是因为 DB 对象没有写成单例。

    Dao:

    @Dao
    interface ItemDao {
        @Query("SELECT * FROM item")
        fun getAll(): LiveData<List<Item>>
    
        @Query("SELECT * FROM item WHERE uid IN (:itemIds)")
        fun loadAllByIds(itemIds: IntArray): List<Item>
    
        @Insert
        fun insert(items: Item): Long
    
    }
    

    AppDatabase

    @Database(entities = [Item::class], version = 1)
    abstract class AppDatabase : RoomDatabase() {
        abstract fun itemDao(): ItemDao
    }
    

    DBUtils

    class DBUtils private constructor() {
    
        companion object {
            val instance: DBUtils by lazy { DBUtils() }
    
            private lateinit var context: Context
            private val database: AppDatabase by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
                Room.databaseBuilder(context, AppDatabase::class.java, "clipboard_manager.db").build()
            }
    
            fun getDatabase(context: Context): AppDatabase {
                this.context = context.applicationContext
                return database
            }
        }
    
    }
    

    使用

    DBUtils.getDatabase(applicationContext).itemDao().getAll().observe(
        this, { items ->
            toast(items.toString())
        }
    )
    

    相关文章

      网友评论

          本文标题:Kotlin + Room + LiveData监听数据库数据变

          本文链接:https://www.haomeiwen.com/subject/fgqvcktx.html