The realm instance is created like shown below:
suspend fun getRealm(): Realm {
val groupId = sessionManager.getGroupId().first()
if (config == null) {
config = SyncConfiguration.Builder(getRealmAppInstance().currentUser(), groupId)
.schemaVersion(REALM_SCHEMA_VERSION)
.build()
}
return Realm.getInstance(config!!)
}
Using the above instance throughout the app.
The below function is in the viewmodel which reads from realm, but it returns empty but data is present in the database.
fun getBpData(){
viewModelScope.launch(Dispatchers.IO) {
val userId = sessionManager.getPrimaryUserId().first()
if (userId != null) {
val realmConfig = RealmConfig(sessionManager)
realmConfig.getRealm()?.let {
val bpDataDao = BpDataDao(it)
val bpData = bpDataDao.getByUserId(userId)
// Check if data is not null
bpData?.let { bp ->
val format = SimpleDateFormat("dd/mm/yyyy")
bp.createdAt?.let { createdDate ->
// Format and udpate UI for date
val strDate = format.format(createdDate)
// Change scope to Main and update UI.
withContext(Dispatchers.Main) {
// Add values to UI using Mutable Live data.
selectedDate.value = strDate
systolic.value = bp.sys ?: ""
diastolic.value = bp.dia ?: ""
pulse.value = bp.pulse ?: ""
}
}
}
}
}
}
}
We are able to write to database but how to read from the database?