0

This is sort of a continuation from my previous one, but I finally figured that one out (got rid of the duplication issue).

Android Room Relationship duplicating information

Customer table

    @Entity(tableName = "customer_table")
    public class Customer {
      @ColumnInfo(name = "Customer_Serial", index = true)
      @PrimaryKey
      private int customerSerial;
    
      @ColumnInfo(name = "Customer_Sort", index = true)
      private String customerSort;

      @ColumnInfo(name = "Customer_Name")
      private String customerName;
    
      public Customer(int customerSerial, String customerName) {
        this.customerSerial = customerSerial;
        this.customerName = customerName;
        this.customerSort = String.format(Locale.ENGLISH, "%d-%d", new Date().getTime(), customerSerial);
      }
    }

Invoice table

    @Entity(tableName = "invoice_table")
    public class Invoice {
      @ColumnInfo(name = "Invoice_Number", index = true)
      @PrimaryKey
      private int invoiceNumber;
    
      @ColumnInfo(name = "Customer_Serial")
      private int customerSerial;
    
      @ColumnInfo(name = "Invoice_Sort", index = true)
      private String invoiceSort;

      @ColumnInfo(name = "Delivery_Status")
      private int deliveryStatus;

      public Invoice(int invoiceNumber, int customerSerial) {
        this.invoiceNumber = invoiceNumber;
        this.customerSerial = customerSerial;
        this.invoiceSort = String.format(Locale.ENGLISH, "%d-%d", new Date().getTime(), invoiceNumber)
      }

      public void setDeliveryStatus(int deliveryStatus) {
        this.deliveryStatus = deliveryStatus;
      }

      public int getDeliveryStatus() { return deliveryStatus; }
    }

CustomerInvoice relation

    public class CustomerInvoice {
      @Embedded public Customer customer;
      @Relation(
        parentColumn = "Customer_Serial",
        entityColumn = "Customer_Serial"
        entity = Invoice.class
      )
      public List<Invoice> invoices;
    }

DAO

   public abstract class InvoiceDao {
     @Transaction
     @Query("SELECT * FROM invoice_table " +
            "JOIN customer_table " +
            "ON invoice_table.Debtor_Ser_No = customer_table.Customer_Serial " +
            "WHERE invoice_table.Delivery_Status = :deliveryStatus " +
            "GROUP BY customer_table.Customer_Serial " +
            "ORDER BY customer_table.Customer_Sort, invoice_table.Invoice_Sort")
    abstract public LiveData<List<CustomerInvoices>> getCustomerInvoices(int deliveryStatus);

    abstract public void insert(Invoice... invoice);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    abstract public void insertCustomer(Customer... customer);
   }

ViewModel public LiveData<List> getCustomerInvoices(int deliveryStatus) { return dao.getCustomerInvoices(); }

Test

    Invoice invoice1 = new Invoice(1234, 1);
    Invoice invoice2 = new Invoice(1235, 1);
    Invoice invoice3 = new Invoice(2468, 2);
    Invoice invoice4 = new Invoice(2469, 2);

    Customer customer1 = new Customer(1, "Customer 1");
    Customer customer2 = new Customer(2, "Customer 2");

    dao.insertCustomer(customer1);
    dao.insertCustomer(customer2);
    dao.insert(invoice1);
    dao.insert(invoice2);
    dao.insert(invoice3);
    dao.insert(invoice4);

    invoice1.setDeliveryStatus(0);
    invoice2.setDeliveryStatus(0);
    invoice3.setDeliveryStatus(0);
    invoice4.setDeliveryStatus(0);
    viewModel.getCustomerInvoices2(0).observe(getViewLifeCycleOwner(), list -> { ... });

If I debug the output of the observer, it returns correctly, 2 customers with 2 invoices each.

However, if I do

Test2

   invoice1.setDeliveryStatus(1);
   viewModel.getCustomerInvoices2(1).observe(getViewLifeCycleOwner(), list -> { ... });

It returns 1 customer with 2 invoices, instead of 1 customer with 1 invoice, as the 2nd invoice for that customer still has a delivery status of 0.

I realise the problem is in the CustomerInvoice relation where it is ignoring the where clause for the invoice_table itself (It still does the customer where clause perfectly).

However I just can't seem to wrap my head around to fix it.

I have Google searched for quite a while now, and I know it is because it is basically just doing 'Get customer where they have at least 1 invoice with the correct delivery status', then it is doing 'Get all invoices for this customer', just that pretty much everything I can find gives basic samples that don't involve LiveData at all, and I need it to be using LiveData.

One of the many attempts I tried to make it work, was to do a lot of the legwork in the viewmodel itself.

DAO

    @Query("SELECT * FROM customer_table " +
            "JOIN invoice_table " +
            "ON customer_table.Customer_Serial = invoice_table.Debtor_Ser_No " +
            "WHERE invoice_table.Delivery_Status = :deliveryStatus " +
            "GROUP BY customer_table.Customer_Serial ORDER BY customer_table.Customer_Sort")
    abstract public Maybe<List<Customer>> getCustomersByDeliveryStatus(int deliveryStatus);

    @Query("SELECT * FROM invoice_table " +
            "WHERE invoice_table.Debtor_Ser_No = :debtorSerial " +
            "AND invoice_table.Delivery_Status = :deliveryStatus " +
            "ORDER BY invoice_table.Invoice_Sort")
    abstract public Single<List<Invoice>> getCustomerInvoicesByDeliveryStatus(int debtorSerial, int deliveryStatus);

ViewModel

public LiveData<List<Map<Customer, List<Invoice>>>> getCustomerInvoices2(int deliveryStatus) {
        MutableLiveData<List<Map<Customer, List<Invoice>>>> liveCustomerInvoices = new MutableLiveData<>();


        List<Map<Customer, List<Invoice>>> listCustomerInvoices = new ArrayList<>();

        mInvoiceDao
                .getCustomersByDeliveryStatus(deliveryStatus)
                .subscribeOn(Schedulers.io())
                .subscribe(
                        (customers) -> {
                            for (Customer customer : customers) {
                                mInvoiceDao.getCustomerInvoicesByDeliveryStatus(
                                        customer.getCustomerSerial(),
                                        deliveryStatus
                                ).subscribeOn(Schedulers.io())
                                        .subscribe(
                                                (invoices) -> {
                                                    listCustomerInvoices.add(Collections.singletonMap(customer, invoices));
                                                }
                                        );
                            }
                            liveCustomerInvoices.postValue(listCustomerInvoices);
                        }, throwable -> Log.e("Error", "Error")
                );

        return liveCustomerInvoices;
    }

While it does work (to a varying degree, the LiveData isn't updated instantly, so sometimes it shows nothing or sometimes it shows 1 thing only until I refresh the display), and my recyclerview shows exactly what I need it to show, it doesn't maintain the order based on 'Customer_Sort' and 'Invoice_Sort' which has to be maintained.

I understand why on that too, it's because 'map' doesn't guarantee order.

Raymond Herring
  • 347
  • 1
  • 3
  • 10

1 Answers1

0

First issue I believe is that when you have @Embedded and then @Relation the @Embedded is considered the parents (Customers). That is Room basically ignores (at first) the children (Invoices).

You appear to be considering this from an Invoice perspective when Room considers it, as instructed by the @Embedded/@Relation, from the Customer perspective.

Once Room has (in theory) obtained the parents (customers) it then considers this from the object perspective and obtains ALL children (invoices), irrespective of SQL (e.g. WHERE ORDER) that affects the children retrieved and builds complete objects (all children for the parent).

The WHERE and ORDER are only affectual if it changes the number of parents.

This basically a convenience approach.

To affect the children (Invoices), prune them, sort them if using the Customer(@Embedded)Invoice(@Realtion) POJO needs a means of overriding Rooms handling.

Another issue is that your testing code changes the Invoice objects (e.g. invoice1.setDeliveryStatus(0);) but does not apply that change to the database. So if you extract from the database then those changes will not have been applied.

Without changing the CustomerInvoice class. Consider the following:-

Getters and setters added to the Customer and Invoice classes.

InvoiceDao transformed to be :-

@Dao
public abstract class InvoiceDao {

   /*
   @Transaction
   @Query("SELECT * FROM invoice_table " +
           "JOIN customer_table " +
           "ON invoice_table.Debtor_Ser_No = customer_table.Customer_Serial " +
           "WHERE invoice_table.Delivery_Status = :deliveryStatus " +
           "GROUP BY customer_table.Customer_Serial " +
           "ORDER BY customer_table.Customer_Sort, invoice_table.Invoice_Sort")
   abstract public LiveData<List<CustomerInvoice>> getCustomerInvoices(int deliveryStatus);

    */

   @Insert(onConflict = OnConflictStrategy.IGNORE)
   abstract public void insert(Invoice... invoice);
   @Insert(onConflict = OnConflictStrategy.IGNORE)
   abstract public void insertCustomer(Customer... customer);
   @Update(onConflict = OnConflictStrategy.IGNORE)
   abstract public void updateInvoice(Invoice... invoices);

   @Query("SELECT customer_table.* " + /* Room does not use the invoice table columns, they are not needed */
           "FROM customer_table " +
           "JOIN invoice_table ON invoice_table.customer_serial = customer_table.Customer_Serial " +
           "WHERE invoice_table.Delivery_Status = :deliveryStatus " +
           "GROUP BY customer_table.Customer_Serial ORDER BY customer_table.Customer_Sort, invoice_table.Invoice_Sort")
   abstract public List<Customer> getApplicableCustomers(int deliveryStatus);
   @Query("SELECT * FROM invoice_table WHERE delivery_status=:deliveryStatus AND customer_serial=:customerSerial ORDER BY invoice_sort" )
   abstract List<Invoice> getApplicableInvoicesForCustomer(int deliveryStatus, int customerSerial);


   @Transaction /* do in a single transaction */
   @Query("") /* trick room so it applies transaction processing logic*/
   public List<CustomerInvoice> getCustomerInvoices(int deliveryStatus) {
      ArrayList<CustomerInvoice> rv = new ArrayList<>();
      for(Customer c: getApplicableCustomers(deliveryStatus)) {
         CustomerInvoice ci = new CustomerInvoice();
         ci.customer = c;
         ci.invoices = getApplicableInvoicesForCustomer(deliveryStatus,c.getCustomerSerial());
         rv.add(ci);
      }
      return rv;
   }
}
  • getCustomerInvoices method commented out
  • updateInvoice method added
  • getApplicableCustomers method added
    • similar to getCustomerInvoices but only gets the Customer fields/column as Room doesn't use the Invoice (the SQL could well be trimmed accordingly).
    • Instead of Debtor_Ser_No customer_serial hard coded.
  • getApplicableInvoicesForCustomer method added (for getting the appropriate invoices)
  • getCustomerInvoices method replaced using a method with body that gets the Customers, as Room does, but then gets the required children (invoices). This combining the getApplicable?? methods and returning the List of CustomerInvoice objects.

To demonstrate a modified Test, that a) updates the invoice delivery_status values in the database and b) uses a method to log the returned CustomerInvoices which allows the required delivery status to be passed:-

  • Note for brevity the mainThread is used.
    public class MainActivity extends AppCompatActivity {
    
        TheDatabase db;
        InvoiceDao dao;
        private static final String TAG = "DBINFO";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            db = TheDatabase.getInstance(this);
            dao = db.getInvoiceDao();
    
            Invoice invoice1 = new Invoice(1234, 1);
            Invoice invoice2 = new Invoice(1235, 1);
            Invoice invoice3 = new Invoice(2468, 2);
            Invoice invoice4 = new Invoice(2469, 2);
    
            Customer customer1 = new Customer(1, "Customer 1");
            Customer customer2 = new Customer(2, "Customer 2");
    
            dao.insertCustomer(customer1);
            dao.insertCustomer(customer2);
            dao.insert(invoice1);
            dao.insert(invoice2);
            dao.insert(invoice3);
            dao.insert(invoice4);
    
            logCustomerInvoices(0,"_R1");
            logCustomerInvoices(1,"_R2");
    
    
            invoice1.setDeliveryStatus(0);
            invoice2.setDeliveryStatus(0);
            invoice3.setDeliveryStatus(0);
            invoice4.setDeliveryStatus(0);
            dao.updateInvoice(invoice1);
            dao.updateInvoice(invoice2);
            dao.updateInvoice(invoice3);
            dao.updateInvoice(invoice4);
            logCustomerInvoices(0,"_R3");
            logCustomerInvoices(1,"_R4");
    
            invoice1.setDeliveryStatus(1);
            invoice2.setDeliveryStatus(0);
            invoice3.setDeliveryStatus(0);
            invoice4.setDeliveryStatus(0);
            dao.updateInvoice(invoice1);
            dao.updateInvoice(invoice2);
            dao.updateInvoice(invoice3);
            dao.updateInvoice(invoice4);
            logCustomerInvoices(0,"_R5");
            logCustomerInvoices(1,"_R6");
    
    
        }
    
        void logCustomerInvoices(int deliveryStatus, String tagSuffix) {
            for(CustomerInvoice ci: dao.getCustomerInvoices(deliveryStatus)) {
                Log.d(TAG+tagSuffix,"Customer is " + ci.customer.getCustomerName() +
                        " Serial is " + ci.customer.getCustomerSerial() +
                        " Sort is " + ci.customer.getCustomerSort() + " There are " + ci.invoices.size() + " Invoices. They are ");
                for (Invoice i: ci.invoices) {
                    Log.d(TAG+tagSuffix,"\n\tInvoice # is " + i.getInvoiceNumber() + " CustSerial is " + i.getCustomerSerial() + " DlvrStatus is " + i.getDeliveryStatus() + " Sort is " +  i.getInvoiceSort());
                }
            }
        }
    }
    

When run 6 sets (3 pairs) of results may be output to the log. The output being:-

2023-02-04 06:53:16.867 D/DBINFO_R1: Customer is Customer 1 Serial is 1 Sort is 1675453996772-1 There are 2 Invoices. They are 
2023-02-04 06:53:16.868 D/DBINFO_R1:    Invoice # is 1234 CustSerial is 1 DlvrStatus is 0 Sort is 1675453996766-1234
2023-02-04 06:53:16.868 D/DBINFO_R1:    Invoice # is 1235 CustSerial is 1 DlvrStatus is 0 Sort is 1675453996771-1235
2023-02-04 06:53:16.869 D/DBINFO_R1: Customer is Customer 2 Serial is 2 Sort is 1675453996772-2 There are 2 Invoices. They are 
2023-02-04 06:53:16.869 D/DBINFO_R1:    Invoice # is 2468 CustSerial is 2 DlvrStatus is 0 Sort is 1675453996771-2468
2023-02-04 06:53:16.869 D/DBINFO_R1:    Invoice # is 2469 CustSerial is 2 DlvrStatus is 0 Sort is 1675453996771-2469


2023-02-04 06:53:16.887 D/DBINFO_R3: Customer is Customer 1 Serial is 1 Sort is 1675453996772-1 There are 2 Invoices. They are 
2023-02-04 06:53:16.887 D/DBINFO_R3:    Invoice # is 1234 CustSerial is 1 DlvrStatus is 0 Sort is 1675453996766-1234
2023-02-04 06:53:16.887 D/DBINFO_R3:    Invoice # is 1235 CustSerial is 1 DlvrStatus is 0 Sort is 1675453996771-1235
2023-02-04 06:53:16.887 D/DBINFO_R3: Customer is Customer 2 Serial is 2 Sort is 1675453996772-2 There are 2 Invoices. They are 
2023-02-04 06:53:16.887 D/DBINFO_R3:    Invoice # is 2468 CustSerial is 2 DlvrStatus is 0 Sort is 1675453996771-2468
2023-02-04 06:53:16.887 D/DBINFO_R3:    Invoice # is 2469 CustSerial is 2 DlvrStatus is 0 Sort is 1675453996771-2469


2023-02-04 06:53:16.906 D/DBINFO_R5: Customer is Customer 1 Serial is 1 Sort is 1675453996772-1 There are 1 Invoices. They are 
2023-02-04 06:53:16.906 D/DBINFO_R5:    Invoice # is 1235 CustSerial is 1 DlvrStatus is 0 Sort is 1675453996771-1235
2023-02-04 06:53:16.906 D/DBINFO_R5: Customer is Customer 2 Serial is 2 Sort is 1675453996772-2 There are 2 Invoices. They are 
2023-02-04 06:53:16.906 D/DBINFO_R5:    Invoice # is 2468 CustSerial is 2 DlvrStatus is 0 Sort is 1675453996771-2468
2023-02-04 06:53:16.906 D/DBINFO_R5:    Invoice # is 2469 CustSerial is 2 DlvrStatus is 0 Sort is 1675453996771-2469
2023-02-04 06:53:16.911 D/DBINFO_R6: Customer is Customer 1 Serial is 1 Sort is 1675453996772-1 There are 1 Invoices. They are 
2023-02-04 06:53:16.911 D/DBINFO_R6:    Invoice # is 1234 CustSerial is 1 DlvrStatus is 1 Sort is 1675453996766-1234
  • R1 (as delivery status's are all 0 returns 2 Customers with 2 Invoices each)
  • R2 returns nothing as there are no Customers with invoices with a delivery status of 1
  • The invoice updates do nothing as the status is already 0, so:-
  • R3 returns all
  • R4 nothing
  • As 1 invoice is changed to have a delivery status of 1 then
  • R5 returns 2 Customer but the first with 1 invoice (as expected) and the other with 2 invoices as expected
  • R6 returns 1 Customer with 1 Invoices who's status is 1
  • Customers and Invoices sorted accordingly.
starball
  • 20,030
  • 7
  • 43
  • 238
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Changing the delivery status does update the database itself. – Raymond Herring Feb 04 '23 at 21:05
  • The other issue is that I need the LiveData. The app will be used on our Cipherlab RS35 handheld computers (with built-in barcode reader), so the moment an invoice barcode is scanned, the RecyclerView needs to reflect this, not to mention every time I have tried to do it without RecylerView, I get a crash in the app telling me not to run it on the main thread. – Raymond Herring Feb 04 '23 at 21:07
  • It is an execllent start, thankyou, the getCustomerInvoices method was what was mainly doing my head in, now I just need it to return a LiveData :) My alternative method was to basically have 3 tables for the invoices, 1 table for each delivery status, and just move the rows between each table as necessary. – Raymond Herring Feb 04 '23 at 21:09
  • To allow running on Main thread add `.allowMainThreadQueries` method to the databasebuilder. – MikeT Feb 04 '23 at 21:09
  • But everywhere I read says to not do that? And it still won't cause the RecyclerView to instantly update? – Raymond Herring Feb 04 '23 at 21:10
  • @RaymondHerring can't help with LiveData side. Not saying to run on main thread but how you can. – MikeT Feb 04 '23 at 21:10
  • Bugger, think I may just have to go the 4 table route then, sucks that Room apparently doesn't have anything to make this easier, and if it does, I haven't found it, a lot of the stuff I have sort of found is Kotlin based, and I'm not ready to figure that language out yet, especially with this app :( – Raymond Herring Feb 04 '23 at 21:11