首页 > 解决方案 > 房间数据库中没有记录保存

问题描述

在我使用它获取数据时将数据插入 RoomDB 后,mindValleyDao.getCategories().value它返回 null

数据库类

@Database(entities = arrayOf(CategoryBO::class), version = 1, exportSchema = false)
abstract class MindValleyDatabase : RoomDatabase(){

    abstract fun mindValleyDao(): MindValleyDao

    companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time.
        @Volatile
        private var INSTANCE: MindValleyDatabase? = null

        fun getDatabase(context: Context): MindValleyDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                        context.applicationContext,
                        MindValleyDatabase::class.java,
                        "mindvalley_database"
                ).allowMainThreadQueries()
                        .fallbackToDestructiveMigration().build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

分类BO.kt

@Entity(tableName = "CategoryEntity")
data class CategoryBO( @PrimaryKey(autoGenerate = true) val id:Int, val name:String)

多阿

@Dao
interface MindValleyDao {

    @Query("SELECT * from CategoryEntity ORDER BY id ASC")
    fun getCategories(): LiveData<List<CategoryBO>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(categoryBO: CategoryBO)
    //suspend fun insert(categoryBO: CategoryBO)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(categoryBOList: List<CategoryBO>)
}

我通过插入类别和获取类别列表来测试它

class MindValleyViewModelNew @Inject constructor() : BaseViewModel() {

    var categoryList: MutableLiveData<List<CategoryBO>> = MutableLiveData()
    private lateinit var mindValleyDao:MindValleyDao

    fun loadDatabase(mContext:Context){
        mindValleyDao = MindValleyDatabase.getDatabase(mContext).mindValleyDao()
        GlobalScope.launch(Dispatchers.IO) {
            mindValleyDao.insert(CategoryBO(0,"first item"))
            val cats = mindValleyDao.getCategories().value
            categoryList.postValue(cats)
        }
    }
}

标签: androidkotlinandroid-roomandroid-viewmodel

解决方案


mindValleyDao.getCategories()返回类型是 LiveData,这就是它异步查询值的原因,你不应该调用.value

Room 中的 LiveData 类型只能用于观察,

如果您想获得价值,请将您的代码修改fun getCategories(): List<CategoryBO>


推荐阅读