'Prevent of creating realm object while saving in RealmList
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
- product A : 3.0
- product A : 2.0
- product B : 5.0
- product C : 3.0
- product C : 2.0
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.
Solution 1:[1]
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
Solution 2:[2]
Instead of using realm.copyToRealm(st)
try using realm.copyToRealmOrUpdate(st)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rohit Sharma |
Solution 2 | Workshed |