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

Android Studio中ListView调用setAdapter()方法导致应用崩溃如何解决

Android应用调用setAdapter崩溃修复方案

崩溃根因

代码中的lv_productList控件未完成初始化,声明该变量后没有在onCreate()方法中调用findViewById()绑定布局中的ListView控件,导致变量为null,调用setAdapter()方法时触发空指针异常,直接造成应用崩溃。

修复步骤

在MainActivity的onCreate()方法中,现有控件初始化代码之后,补充ListView的绑定逻辑:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn_add = findViewById(R.id.btn_add);
    btn_viewAll = findViewById(R.id.btn_viewAll);
    et_name = findViewById(R.id.et_name);
    et_number = findViewById(R.id.et_number);
    // 补充下面这一行,注意将R.id.lv_product替换为你布局文件中ListView控件实际设置的id
    lv_productList = findViewById(R.id.lv_product);
    // 其余原有代码保持不变
}

补充说明

如果完成上述修改后仍出现崩溃,请抓取Logcat中的崩溃堆栈日志,根据报错信息进一步定位问题。目前你的ProductModel已经重写了toString()方法,搭配系统自带的android.R.layout.simple_list_item_1布局使用ArrayAdapter逻辑正常,无需修改适配器相关代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:15:00