Black_Magician
Black_Magician

Reputation: 35

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

  1. product A : 3.0
  2. product A : 2.0
  3. product B : 5.0
  4. product C : 3.0
  5. 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.

Upvotes: 0

Views: 499

Answers (2)

Workshed
Workshed

Reputation: 246

Instead of using realm.copyToRealm(st) try using realm.copyToRealmOrUpdate(st)

Upvotes: 0

Rohit Sharma
Rohit Sharma

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

Related Questions