Search code examples
androidandroid-roomandroid-livedata

Application Crashes and showing null exception when room database is empty and try to run this query


Query:

@Query("SELECT SUM(productPrice) FROM VitalCafeCart")
    LiveData<Integer> getSum();

and the result of this working fine when database have rows in it. i am using observer to get result.

here is the observer code.

LiveData<Integer> sum = AppDatabase.getInstance(mContext).atcDao().getSum();
            Observer<Integer> cartTotalObserver = new Observer<Integer>() {
                @Override
                public void onChanged(Integer integer) {

                        if (integer == 0) {
                            linearGotoCart.setVisibility(View.GONE);
                        } else {
                            shopDetailsTotalPrice.setText("Rs."+String.valueOf(integer));
                            linearGotoCart.setVisibility(View.VISIBLE);
                        }

                }
            };
            sum.observe(getActivity(), cartTotalObserver);

Solution

  • You could use :-

    @Query("SELECT coalesce(SUM(productPrice),0) FROM VitalCafeCart")
    

    The coalesce function uses the first non-null value and hence 0 if the sum is null.

    or you could use

    @Query("SELECT total(productPrice) FROM VitalCafeCart")
    

    The total aggregate function being the equivalent of sum never returning null but instead 0.0