I have a project that uses 3 Realm models: Pantry, Department and Market. The Pantry and Department have a 1 to many relationship and the Pantry and Market have a many to many relationship, and all 3 are shown below. The issue is that I (being new to Realm and to databases in general) am having dificulties saving and updating the models. In general the Pantry model saves well, but the other 2 don't. The idea is: the Department saves many Pantry items, the Pantry item saves only 1 Department item. The Pantry item can save many Markets and the Market item can save many Pantry items.
When the database is totally empty saving the first item goes smoothly.
Then on entering a new item which falls on an existing and/or Market, a new item is created in the Department and Market models; instead of adding to the existing.
I have been unsuccessful in finding documentation on 1 to may and many to many schemas. I have found how to create the models and that's how I have created them but not how to use them for inputing records and how to save (housekeeping).
I tried querying for the existing department and market and when the query is successful and it is used on new items, the app crashes. I have followed it, by use of the debugger and by logs and all seems ok, yet the app crashes. I have not reviewed the general logs, since I would not understand anything unless its completely simple.
The models:
class Pantry: RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var itemName: String = ""
var department: Department? = null
var market: RealmList<Market> = realmListOf()
var brand: String = ""
var size: String = ""
var price: String = ""
var date: String = ""
var checkToAdd: Boolean = false
var checkChecked: Boolean = false
}
class Department: RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var deptName: String = ""
var pantry: RealmList<Pantry> = realmListOf()
}
class Market: RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var marketName: String = ""
val pantryItems: RealmResults<Pantry> by backlinks(Pantry::market)
}
The query to find the existing department:
fun checkDeptName(dName: String): Pantry? {
val existingItem = realm.query<Pantry>(query = "department.deptName == $0", dName.lowercase()).first().find()
if (existingItem != null) {
Log.d("WALRUS", "Inside the function: ${existingItem.department?.deptName}")
return existingItem
}
else {
return null
}
}
The query to find existing market:
fun getMarketByMarketName(marketName: String): Market? {
val allPantries = realm.query<Pantry>().find()
for (pantry in allPantries) {
val market = pantry.market.find { it.marketName == marketName }
if (market != null) {
Log.d("WALRUS", "Inside the function: ${market.marketName}")
return market
}
}
return null
}
The function to add a new pantry item to the database:
fun addPantryItem(
name: String,
dept: String,
myMarket: String,
brandName: String,
sizeName: String,
priceName: String
){
// Find the market by the name and update the pantry item
Log.d("WALRUS", "Just Before saving the market item")
val existingMarket = getMarketByMarketName(myMarket)
val pantry1 = Pantry().apply {
itemName = name
if (existingMarket != null){
Log.d("WALRUS", "Found existing market: ${existingMarket.marketName}")
market = realmListOf(existingMarket)
} else {
Log.d("WALRUS", "Did NOT find existing market")
market = realmListOf(Market().apply { marketName = myMarket })
}
if(brandName.isNotEmpty()) brand = brandName
if(sizeName.isNotEmpty()) size = sizeName
if(priceName.isNotEmpty()) price = priceName
}
val existDepartment = checkDeptName(dept)
if (existDepartment != null){
Log.d("WALRUS", "Found existing department: ${existDepartment.department?.deptName}")
pantry1.department = existDepartment.department
}else{
Log.d("WALRUS", "Did NOT find Existing department")
val department1 = Department().apply {
deptName = dept
pantry = realmListOf(pantry1)
}
pantry1.department = department1
}
Log.d("WALRUS", "Reached just before the vms.launch")
viewModelScope.launch {
realm.write {
copyToRealm(pantry1, updatePolicy = UpdatePolicy.ALL)
}
}
Log.d("WALRUS", "Reached the save pantry and ready to clear val's")
//Clear all val's
_itemName.value = ""
_dept.value = ""
_pantryMarket.value = ""
_brand.value = ""
_size.value = ""
_price.value = ""
}
I believe that is the relevant information. The issue is to add 1 item, because adding items in bulk, is easy and no problems. Here is a sample:
fun createSampleEntries(){
viewModelScope.launch {
realm.write {
// MARKETS
val market1 = Market().apply {
marketName = "Keys-Food"
}
val market2 = Market().apply {
marketName = "Publix"
}
// PANTRY ITEMS
val pantry1 = Pantry().apply {
itemName = "shampoo"
market = realmListOf(market2)
brand = "L'Oreal"
}
val pantry2 = Pantry().apply {
itemName = "deodorant"
market = realmListOf(market2)
brand = "Brut"
}
val pantry3 = Pantry().apply {
itemName = "earbuds"
market = realmListOf(market2)
brand = "Johnson & Johnson"
}
val pantry4 = Pantry().apply {
itemName = "sugar"
market = realmListOf(market1, market2)
brand = "Domino"
}
val pantry5 = Pantry().apply {
itemName = "water"
market = realmListOf(market1, market2)
brand = "Zephyrhills"
}
//DEPARTMENTS
val department1 = Department().apply {
deptName = "toiletries"
pantry = realmListOf(pantry1, pantry2, pantry3)
}
val department2 = Department().apply {
deptName = "baking goods"
pantry = realmListOf(pantry4)
}
val department3 = Department().apply {
deptName = "beverages"
pantry = realmListOf(pantry3)
}
pantry1.department = department1
pantry2.department = department1
pantry3.department = department1
pantry4.department = department2
pantry5.department = department3
copyToRealm(pantry1, updatePolicy = UpdatePolicy.ALL)
copyToRealm(pantry2, updatePolicy = UpdatePolicy.ALL)
copyToRealm(pantry3, updatePolicy = UpdatePolicy.ALL)
copyToRealm(pantry4, updatePolicy = UpdatePolicy.ALL)
copyToRealm(pantry5, updatePolicy = UpdatePolicy.ALL)
}
}
}
The reason its easy is because the models are there ( pantry1, pantry2, department1, market1, etc).
But on a 1 item at a time, is a different story. I need to get back department1 and the market1. How is it done. That is the question.....
Any guidance as to where to look for information on this matter will be greatly appreciated.