Search code examples
javaandroiddatabaserealm

Insert Multiple Rows realm android


Hello ive been trying to insert multiple rows to my realm database using values from arraylists , whenever i try to insert through a for loop it only adds the last one, if you need something else (code, xml) pls let me know

here is my code:

 realm.executeTransactionAsync(new Realm.Transaction() { //ASYNCHRONOUS TRANSACCION TO EXECUTE THE QUERY ON A DIFFERENT THREAD
                        @Override
                        public void execute(Realm bgRealm) {
                            // increment index
                            Invoices inv = bgRealm.createObject(Invoices.class, RealmController.autoincrement(bgRealm, Invoices.class)); //METHOD THAT GIVES US THE AUTONINCREMENTE FUNCTION
                            //inv.id = nextId;                                                                                           //THE 2ND PARAMETER IN CREATE OBJECTE DEFINES THE PK
                            //...
                            //realm.insertOrUpdate(user); // using insert API


                            inv.number = n;
                            inv.serial = s;
                            inv.client = c;
                            inv.subtotal = sub;
                            inv.tax = tax;
                            inv.total = tot;

                            Invoice_lines invl = bgRealm.createObject(Invoice_lines.class, RealmController.autoincrement(bgRealm, Invoice_lines.class));//ID FROM ANOHTER TABLE (ROW)

                            for(int i=0; i<price.size(); i++) {
                                invl.description = description.get(i);
                                invl.price = price.get(i);
                                invl.quantity = quantity.get(i);
                                invl.invoice = inv;
                                bgRealm.insert(invl);
                            }

                        }
                    }

Solution

  • I'm not sure. You create only one realm object in this line:

    Invoice_lines invl = bgRealm.createObject(Invoice_lines.class, RealmController.autoincrement(bgRealm, Invoice_lines.class));//ID FROM ANOHTER TABLE (ROW)
    

    And in cycle you change invl fields, but don't insert new objects.

    Try to create objects inside cycle.