I've got a repository which gets a list of values from the Room Database. I have two Fragments: one contains a RecyclerView which displays values from this repository, and a DialogFragment in which I add a new value to the database. I use different DAOs and though a new value is added to the Database, the list in the Fragment doesn't change though Database Inspector shows that a new value is in the db. Here's my Database code.
@Database(entities = [DatabaseBand::class], version = 1, exportSchema = false)
abstract class BandsDatabase : RoomDatabase() {
abstract val bandDatabaseDao: BandDatabaseDao
companion object {
@Volatile
private var INSTANCE: BandsDatabase? = null
fun getInstance(context: Context): BandsDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(context.applicationContext,
BandsDatabase::class.java,
"test_band_database")
.fallbackToDestructiveMigration()
.setJournalMode(JournalMode.TRUNCATE)
.build()
}
return instance
}
}
}
}
What's the right way to solve this problem? Pass the DAO as an argument or insert values to the db only in the Fragment that contains that DAO?
Edit:
In the Main Fragment I have ViewModel that contains LiveData<List<DatabaseBand>>
property. There I also have a DAO. In the DialogFragment I have another DAO (in both Fragments I use application context to get the DAO). I just insert a new Item into the DB.
In the DAO I use this query:
@Query("SELECT * FROM bands_table")
fun getAll(): LiveData<List<DatabaseBand>>
It returns LiveData, I observe it. When I add an element using another DAO the observer doesn't trigger. When I use DAO from this Fragment or pass it as an argument everything works fine.