I'm trying to add an entry into local DB but it's not working for me. It says 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)
}
I'm trying to insert using an adapter:
GlobalScope.launch {
AppDatabase.appListDao().saveFavorites(entity)
}
But here appListDao
called as unknown reference. Hope my query is cleared. Thanks in advance.
CodePudding user response:
It's because of that you must create instance of AppDabase and then on instance of it call the dao function like this:
create a file 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!!
}
}
}
and when your code must be change to this:
GlobalScope.launch {
DatabaseSingleton.getAppDatabase(
context
).appListDao().saveFavorites(entity)
}