Android Studio添加首条数据库数据后应用崩溃问题求助
问题分析
崩溃核心是空指针异常:TypeAdapter.onBindViewHolder方法中调用holder.tvName.setText()时,holder.tvName为null。无数据时RecyclerView的getItemCount()为0,不会执行onBindViewHolder,因此不会崩溃;有数据时触发该方法,暴露空指针问题。
修复方案
1. 修正布局文件ID匹配问题(直接解决崩溃)
TypeAdapter.TypeViewHolder中通过R.id.tvTypeName查找TextView,但你的layoutitem.xml中对应TextView的ID可能不匹配,导致holder.tvName为null。
操作步骤:
打开layoutitem.xml,确保显示类型名称的TextView ID为tvTypeName,示例代码:
<TextView android:id="@+id/tvTypeName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" />
2. 优化数据库查询方法,避免潜在错误
TypeDataQuery.getAll()存在硬编码列索引的问题,表结构变化会直接报错,同时增加Cursor有效性判断增强鲁棒性:
public static ArrayList<Type> getAll(Context context) { ArrayList<Type> lstType = new ArrayList<>(); UserDBHelper userDBHelper = new UserDBHelper(context); SQLiteDatabase db = userDBHelper.getReadableDatabase(); Cursor cs = db.rawQuery("Select * from " + utils.TABLE_TYPE, null); // 判断Cursor有效且存在数据 if (cs != null && cs.moveToFirst()) { do { // 通过列名获取索引,避免硬编码 int id = cs.getInt(cs.getColumnIndexOrThrow(utils.COLUMN_TYPE_ID)); String name = cs.getString(cs.getColumnIndexOrThrow(utils.COLUMN_TYPE_NAME)); Type type = new Type(id, name); lstType.add(type); } while (cs.moveToNext()); cs.close(); } db.close(); return lstType; }
3. 增强Adapter的空值判断
在TypeAdapter.onBindViewHolder中增加多维度空值判断,避免崩溃:
@Override public void onBindViewHolder(@NonNull TypeViewHolder holder, int position) { Type item = lstType.get(position); if(item != null && holder.tvName != null) { holder.tvName.setText(item.getName()); // 确保回调接口不为空再调用 if(typeCallBack != null) { holder.ivEdit.setOnClickListener(view -> typeCallBack.onItemEditClicked(item, position)); holder.ivDelete.setOnClickListener(view -> typeCallBack.onItemDeleteClicked(item, position)); } } }
4. 优化Activity列表初始化
避免不必要的对象创建,同时处理getAll()返回null的极端情况:
// 替换原初始化代码 lstType = TypeDataQuery.getAll(this); if(lstType == null) { lstType = new ArrayList<>(); }
内容的提问来源于stack exchange,提问作者Random guy
相关产品推荐
相关产品推荐

