You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView无法加载数据库数据,页面崩溃退回HomeActivity

解决RecyclerView展示数据库数据崩溃问题

核心错误排查与修复步骤

1. 修复CustomAdapter的语法错误

在CustomAdapter的MyViewHolder类中存在一行不完整的冗余代码,直接删除即可:

// 删除此行无效代码
LinearLayout

这行代码会导致编译失败,是引发页面崩溃的直接原因之一。

2. 关闭Cursor避免内存泄漏与异常

在ToolsActivity的storeDataInArrays()方法中,使用完Cursor后必须关闭,否则会引发内存泄漏或运行时异常:

void storeDataInArrays() {
    Cursor cursor = myDB.readAllData();
    if(cursor.getCount() == 0) {
        Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
    } else {
        while (cursor.moveToNext()) {
            toolId.add(cursor.getString(0));
            toolName.add(cursor.getString(1));
            toolModule.add(cursor.getString(2));
            toolDescription.add(cursor.getString(3));
        }
    }
    // 新增:使用完毕后关闭Cursor
    if (cursor != null) {
        cursor.close();
    }
}

3. 给Adapter的ArrayList指定泛型

CustomAdapter中的ArrayList未指定泛型,可能引发类型转换问题,修改为:

// 成员变量指定String泛型
private ArrayList<String> tool_id, tool_name, tool_module, tool_description;

// 构造方法同步更新参数类型
CustomAdapter(Context context, ArrayList<String> tool_id, ArrayList<String> tool_name, ArrayList<String> tool_module, ArrayList<String> tool_description) {
    this.context = context;
    this.tool_id = tool_id;
    this.tool_name = tool_name;
    this.tool_module = tool_module;
    this.tool_description = tool_description;
}

4. 检查RecyclerView Item布局文件

确保costum_item_list.xml(建议修正拼写为custom_item_list.xml避免错误)中存在以下ID的TextView:

  • toolID
  • toolName
  • toolModule
  • toolDescription
    同时确认布局文件无XML语法错误。

5. 优化数据库查询操作(可选)

在DBHelper的readAllData()方法中,使用getReadableDatabase()替代getWritableDatabase(),查询操作无需写入权限:

Cursor readAllData () {
    String query = "SELECT * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = null;
    if(db != null) {
        cursor = db.rawQuery(query, null);
    }
    return cursor;
}

完成以上修改后,重新编译运行即可解决页面崩溃和数据不显示的问题。

内容的提问来源于stack exchange,提问作者Jasin Avdiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:31:20