Room数据库为空时执行SUM查询触发空异常致应用崩溃如何解决
问题原因
SQLite的SUM()聚合函数在目标查询表无数据时,返回结果为NULL而非0。你的DAO方法返回类型为LiveData<Integer>,空表场景下Observer的onChanged回调收到的integer参数为null,未做判空处理直接判断integer == 0时会触发空指针异常,导致应用崩溃。
修复方案
推荐优先从SQL查询层面统一处理,也可以选择在业务代码回调层处理:
方案1:SQL层兜底返回值(推荐)
修改DAO的查询语句,通过IFNULL()函数将SUM()的返回结果兜底为0,从根源避免null返回:
@Query("SELECT IFNULL(SUM(productPrice), 0) FROM VitalCafeCart") LiveData<Integer> getSum();
修改完成后原有Observer逻辑无需调整,空表场景下会自动返回0,完全匹配你原有判断逻辑。
方案2:Observer回调层判空
如果不想修改原有DAO查询逻辑,直接在onChanged回调中增加null处理即可:
Observer<Integer> cartTotalObserver = new Observer<Integer>() { @Override public void onChanged(Integer integer) { // 空表返回null时等价为总额0 int cartTotal = integer == null ? 0 : integer; if (cartTotal == 0) { linearGotoCart.setVisibility(View.GONE); } else { shopDetailsTotalPrice.setText("Rs." + cartTotal); linearGotoCart.setVisibility(View.VISIBLE); } } };
内容的提问来源于stack exchange,提问作者Walid Ahmed
相关产品推荐
相关产品推荐

