Android开发遇空指针错误:调用ImageView.setImageDrawable时对象为null 求修复方案
问题原因分析
该报错核心是调用setImageDrawable方法的ImageView对象为空,触发空指针,有两个直接诱因:
- 你仅为
img数组的前2个元素(img[0]、img[1])做了findViewById布局绑定,但img数组总长度为7,当逻辑中i累加到2及以上时,img[i]没有对应绑定的控件,自然为空对象 - 你的
info数组长度仅为2,当i>=2时访问info[i]同样会触发空指针或数组越界,当前仅先触发了ImageView的空指针报错
修复方案
- 首先检查你的布局文件,确认所有需要用到的ImageView、TextView的控件ID,给img数组所有用到的元素补全绑定逻辑,你代码中用到了img[0]~img[5],所以要补全剩下的绑定:
img[0] = findViewById(R.id.content_disease1); img[1] = findViewById(R.id.content_disease2); // 补全剩余需要用到的img元素绑定,ID对应你布局文件里的实际ID img[2] = findViewById(R.id.content_disease3); img[3] = findViewById(R.id.content_disease4); img[4] = findViewById(R.id.content_disease5); img[5] = findViewById(R.id.content_disease6);
- 同步修改info数组的长度,匹配你实际用到的数量,同时补全所有info元素的绑定:
// 原代码长度为2,修改为你实际需要的长度,比如6 TextView info[] =new TextView[6]; // 补全绑定 info[0] = findViewById(R.id.info1); info[1] = findViewById(R.id.info2); info[2] = findViewById(R.id.info3); info[3] = findViewById(R.id.info4); info[4] = findViewById(R.id.info5); info[5] = findViewById(R.id.info6);
- 检查是否漏写布局加载逻辑:你当前
onCreate方法中没有调用setContentView()加载对应布局文件,漏写这行会导致所有findViewById都返回空,必须在super.onCreate(savedInstanceState)之后第一行补全:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 补全这行,替换为你实际的布局文件名 setContentView(R.layout.activity_check_disease); // 后续的findViewById逻辑 }
- 可额外增加非空判断避免类似问题:
if(img[i] != null){ img[i].setImageDrawable(getResources().getDrawable(R.drawable.d1)); } if(info[i] != null){ info[i].setVisibility(View.VISIBLE); // 其余info相关操作 }
内容的提问来源于stack exchange,提问作者Revaldo Kusiman
相关产品推荐
相关产品推荐

