android - 房间数据库中没有记录保存
问题描述
在我使用它获取数据时将数据插入 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)
}
}
}
解决方案
mindValleyDao.getCategories()
返回类型是 LiveData,这就是它异步查询值的原因,你不应该调用.value
Room 中的 LiveData 类型只能用于观察,
如果您想获得价值,请将您的代码修改fun getCategories(): List<CategoryBO>
为
推荐阅读
- ios - Xcode 找不到任何与“应用程序名称”匹配的 iOS 应用程序开发配置文件
- java - 如何修复异常:getOutputStream() 已为此响应调用?
- python - 如何在 Python 的图形中同时使用字符串和数字标记 x&y 值
- python - 如何删除熊猫数据框中的多个标题行
- java - 如何为我的代码设置限制问题
- javascript - 如何删除文档数组中的键
- sql-server - SqlBulkCopy 和 datetime2 目标数据库列
- javascript - 笑话:如何模拟从 index.js 文件导出的自定义模块?
- visual-studio-code - 格式化程序在 lineSplit 上的 VSCode 中不起作用
- typescript - 创建泛型类型实例的通用存储库