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

Android应用启动报Unable to start activity错误闪退问题求助

问题根因
  • 崩溃触发点:ArrayAdapter 内部调用传入列表的size()方法时,拿到的列表是null,触发空指针异常
  • 根本原因:FileHelper.readData()方法的异常处理逻辑不完整
    • 首次启动应用时,存储数据的listinfo.dat文件不存在,会触发FileNotFoundException
    • 捕获该异常后仅打印堆栈,没有给itemList初始化空的ArrayList,最终返回null
    • MainActivity中把原本初始化好的空ArrayList覆盖为null,传给ArrayAdapter后触发崩溃
修复方案

方案1:修改FileHelper的readData方法,所有异常分支都返回非空列表(更推荐)

直接在方法初始化时就给默认空列表,所有异常场景都不会返回null:

public  static  ArrayList<String> readData(Context context){
    // 初始化默认空列表,避免异常场景返回null
    ArrayList<String> itemList = new ArrayList<>();

    try {
        FileInputStream fis = context.openFileInput(FILENAME);
        ObjectInputStream ois = new ObjectInputStream(fis);
        try {
            itemList = (ArrayList<String>) ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return itemList;
}

方案2:在MainActivity接收返回值时做非空兜底

如果不想修改FileHelper的逻辑,也可以在MainActivity赋值时增加非空判断:

itemList = FileHelper.readData(this);
// 非空兜底,避免拿到null值传给Adapter
if(itemList == null){
    itemList = new ArrayList<>();
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,android.R.id.text1,itemList);
可选优化点
  • 给添加按钮增加输入校验,避免用户输入空内容直接添加到列表
  • 读写文件的异常场景可增加用户友好提示,比如用Toast告知用户数据加载/保存失败

内容的提问来源于stack exchange,提问作者Khalid Moutaouakil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:45:03