Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading