如何使用协程向 Room 添加条目
How to add an entry into Room using Coroutines
我正在尝试向本地数据库中添加一个条目,但它对我不起作用。它说 unresolved reference
.
RoomClass.kt
@Database(entities = [ApodEntity::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun appListDao(): AppDao
}
Dao.kt
@Dao
interface AppDao {
@Insert()
fun saveFavorites(item: AppEntity)
}
我正在尝试使用适配器插入:
GlobalScope.launch {
AppDatabase.appListDao().saveFavorites(entity)
}
但这里 appListDao
称为未知引用。希望我的查询被清除。提前致谢。
这是因为你必须创建 AppDabase 的实例,然后在它的实例上调用 dao 函数,如下所示:
创建文件DatabaseSinglton.kt
object DatabaseSingleton {
var database: AppDatabase? = null
fun getAppDatabase(context: Context): AppDatabase {
return if (database == null) {
database = Room.databaseBuilder(
context,
AppDatabase::class.java,
"AppDatabase"
).build()
database!!
} else {
database!!
}
}
}
当您的代码必须更改为:
GlobalScope.launch {
DatabaseSingleton.getAppDatabase(
context
).appListDao().saveFavorites(entity)
}
我正在尝试向本地数据库中添加一个条目,但它对我不起作用。它说 unresolved reference
.
RoomClass.kt
@Database(entities = [ApodEntity::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun appListDao(): AppDao
}
Dao.kt
@Dao
interface AppDao {
@Insert()
fun saveFavorites(item: AppEntity)
}
我正在尝试使用适配器插入:
GlobalScope.launch {
AppDatabase.appListDao().saveFavorites(entity)
}
但这里 appListDao
称为未知引用。希望我的查询被清除。提前致谢。
这是因为你必须创建 AppDabase 的实例,然后在它的实例上调用 dao 函数,如下所示:
创建文件DatabaseSinglton.kt
object DatabaseSingleton {
var database: AppDatabase? = null
fun getAppDatabase(context: Context): AppDatabase {
return if (database == null) {
database = Room.databaseBuilder(
context,
AppDatabase::class.java,
"AppDatabase"
).build()
database!!
} else {
database!!
}
}
}
当您的代码必须更改为:
GlobalScope.launch {
DatabaseSingleton.getAppDatabase(
context
).appListDao().saveFavorites(entity)
}