传递ArrayList数据时ImageView.setImageResource空对象引用异常求助
解决NullPointerException:ImageView.setImageResource调用时对象为空的问题
嘿,我一眼就发现你遇到的问题根源啦!你看到的错误void android.widget.ImageView.setImageResource(int) on a null object reference,本质是你在还没初始化ImageView实例的时候,就调用了它的setImageResource方法。
看你PageActivity里的这段代码:
//receive data Intent intent = getIntent(); int image = intent.getExtras().getInt("Thumbnail"); //set value img.setImageResource(image); img = findViewById(R.id.pageImage);
这里的执行顺序完全搞反了:你先尝试给img设置图片资源,但此时img还是null(因为还没执行findViewById去获取布局里的ImageView实例),自然就抛出空指针异常了。
修复方案
只需要调换两行代码的顺序,先初始化img,再调用setImageResource:
//receive data Intent intent = getIntent(); int image = intent.getExtras().getInt("Thumbnail"); // 先获取ImageView实例 img = findViewById(R.id.pageImage); // 再设置图片资源 img.setImageResource(image);
额外注意事项
- 确认你的
activity_page.xml布局文件中,确实存在一个id为pageImage的ImageView,如果id拼写错误或者不存在,findViewById还是会返回null。 - 另外,建议你在获取Intent extras的时候做个非空判断,避免因为没有传递数据导致的异常,比如:
Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { int image = intent.getExtras().getInt("Thumbnail"); img = findViewById(R.id.pageImage); img.setImageResource(image); }
这样就能解决你当前的空指针问题啦!
内容的提问来源于stack exchange,提问作者Simone Atzeni
相关产品推荐
相关产品推荐

