Android Studio用RecyclerView展示数据库数据,报element == null错误如何解决
报错原因及修复方案
核心报错原因
element == null本质是触发了空指针异常,问题出在Product对象的total属性为空,你在DataBaseHelper的getEveryone()方法里只读取了name、price、quantity三个字段,没有读取数据库中存储的COLUMN_TOTAL字段,构造Product实例时也没有给total属性赋值,如果你的Product类中total是包装类Float且没有默认值,默认就是null,后续Adapter的onBindViewHolder中调用product.getTotal()时就会触发空指针。- 额外逻辑问题:新增商品后没有更新RecyclerView数据源、也没有通知适配器刷新,会导致新增后列表不更新;delete方法SQL语法错误,字符串匹配没有加引号也可能触发异常。
修复步骤
1 修复数据库查询逻辑
修改DataBaseHelper的getEveryone()方法,补全total字段读取逻辑:
public List<Product> getEveryone(){ List<Product> returnList = new ArrayList<>(); String queryString = "SELECT * FROM " + NAME_TABLE; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(queryString, null); if(cursor.moveToFirst()){ do{ String name = cursor.getString(1); float price = cursor.getFloat(2); int quantity = cursor.getInt(3); // 新增读取total字段的逻辑 float total = cursor.getFloat(4); Product newProduct = new Product(name, price, quantity); // 给total属性赋值,如果你的Product有带四个参数的构造方法也可以直接传入 newProduct.setTotal(total); returnList.add(newProduct); }while(cursor.moveToNext()); } cursor.close(); db.close(); return returnList; }
2 修复新增商品逻辑
修改DataActivity中添加按钮的点击事件,补全total赋值、新增后刷新列表的逻辑:
bt_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Product p = new Product(); try { p.setName(et_name.getText().toString()); float price = Float.parseFloat(et_price.getText().toString()); int qty = Integer.parseInt(et_qty.getText().toString()); p.setPrice(price); p.setQuantity(qty); // 补全total计算逻辑,否则存入数据库的total也是null p.setTotal(price * qty); } catch (Exception e){ Toast.makeText(DataActivity.this,"输入有误,请检查:"+e,Toast.LENGTH_SHORT).show(); // 输入异常直接返回,不要插入无效数据 return; } DataBaseHelper dataBaseHelper = new DataBaseHelper(DataActivity.this); boolean addSuccess = dataBaseHelper.addOne(p); if (addSuccess) { Toast.makeText(DataActivity.this,"添加成功",Toast.LENGTH_SHORT).show(); // 刷新列表数据 productList.clear(); fillProductList(myDb); mAdapter.notifyDataSetChanged(); // 清空输入框 et_name.setText(""); et_price.setText(""); et_qty.setText(""); } else { Toast.makeText(DataActivity.this,"添加失败",Toast.LENGTH_SHORT).show(); } } });
3 检查条目布局文件
确认你的res/layout/itemlayout.xml中存在四个TextView,id分别为tv_name、tv_price、tv_qty、tv_total,如果id不匹配,findViewById会返回null,赋值时也会触发空指针。
可选:修复删除方法SQL语法
public boolean deleteOne(Product product){ SQLiteDatabase db = this.getWritableDatabase(); // 用参数化查询避免SQL注入,也解决字符串需要加引号的问题 int deleteRows = db.delete(NAME_TABLE, COLUMN_NAME + "=?", new String[]{product.getName()}); db.close(); return deleteRows > 0; }
内容的提问来源于stack exchange,提问作者Don'thavetHanswers
相关产品推荐
相关产品推荐

