Reputation: 35
I have two model classes, Product and StoreTransaction like below here
Product.kt
open class Product(
var barcode: String? = null,
var name: String? = null,
var price: Double? = null,
var quantity: Double? = null
) : RealmObject()
StoreTransaction.kt
open class StoreTransaction(
var date: Date? = null,
var productList: RealmList<Product>? = null
// and other variables below
) : RealmObject()
Here we have 3 products, Product A, B and C with the same quantity of 5 pcs each
Then i buy product A and C 2 pcs each and save the transaction like this
fun saveTransaction(toBuyList: ArrayList<Product>, realm: Realm) {
val date = Date()
val productList = RealmList<Product>()
productList.addAll(toBuyList.toList())
// other variables
val st = StoreTransaction(date, productList // other vars)
realm.executeTransaction {
realm.copyToRealm(st)
// update stock quantity
toBuyList.forEach { itemToBuy ->
val product = realm.where(Product::class.java)
.equalTo("barcode", itemToBuy.barcode).findFirst()
product?.quantity = product?.quantity?.minus(itemToBuy.quantity!!)
}
}
}
When i query back my product i got the following result
it seems saving a product RealmList in StoreTransaction class creates new data in Product class. Is there a way to prevent this? i'm trying not to display the sold product.
now i know that i can create an extra variable in Product class like a boolean that indicates the product is sold or not and then query it. But is it the right way?
side note: my current solution right now is changing the productList property in StoreTransaction into string (by using Gson) for temporary. it works well and fine but im curios if there is a better way to handle this.
Upvotes: 0
Views: 499
Reputation: 246
Instead of using realm.copyToRealm(st)
try using realm.copyToRealmOrUpdate(st)
Upvotes: 0
Reputation: 1414
Use @PrimaryKey Annotation over barcode
public class TestObj extends RealmObject {
@PrimaryKey
private String code;
}
Like I Do it in Java Basically Object need to have a primary key to update existing object in the database
Upvotes: 1