we have a ROOM database with a table containing a Date field and and an amount field. The Date field is the (@NonNull) primary key. An initial query counts the number of records where the date <= an input date. If the first query returns a result > 0, a second query selects the maximum date using the same criteria, and a third query retrieves the record with that maximum date and returns the value of the amount field. The logic behind this was: is there a date -> if so, what is the date -> use the date to find the amount.
the DAO contains:
@Query("SELECT COUNT(*) FROM theTable WHERE date_field <= :inputDate")
int runFirstQuery (Date inputDate);
@Query("SELECT MAX(date_field) FROM theTable WHERE date_field <= :inputDate")
Date runSecondQuery (Date inputDate);
@Query("SELECT * FROM theTable WHERE date_field = :inputDate")
TableEntity getRecord (Date inputDate);
in the activity:
BigDecimal theAmount = BigDecimal.ZERO;
Date theInputDate = someCalendarWhichIsntTheProblem.getTime();
int checkForRecords = theDatabase.theDAO.runFirstQuery(theInputDate);
if (checkForRecords > 0){
Date resultDate = theDatabase.theDAO.runSecondQuery(theInputDate);
theAmount = theDatabase.theDAO.getRecord(resultDate).getTheAmount();
}
This code has been performing correctly without incident since publication (several years now), but recently the last line referenced above threw a null pointer exception somewhere in the wild (twice, on the same day, for the same user), and I haven't been successful in duplicating the error behavior. As I understand the logic here, the NPE would be thrown only if resultDate == null, but how would that be possible since a) the date field can’t contain a null value and b) we checked for matching records before running the second query? There must be at least one record found by the first query in order for the second query to be executed, so what's missing here?