setImageResource到drawables数组会抛出nullpointer异常

时间:2014-11-22 08:03:28

标签: android nullpointerexception

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_orbital);
    Intent i = getIntent();
    Integer[] orbitalBodies = {R.drawable.dres, R.drawable.duna, R.drawable.eeloo, R.drawable.eve, R.drawable.jool, R.drawable.kerbin, R.drawable.kerbol, R.drawable.moho};
    int planetId = i.getExtras().getInt("intOrbitalId");
    ImageView img = (ImageView)findViewById(R.id.image);
    img.setImageResource(orbitalBodies[planetId]); //this throws nullpointerexception
}

在调试中,我能够确认orbitalBodies [planetId]为drawables返回正确的整数值。我无法解决这个小问题

2 个答案:

答案 0 :(得分:2)

int数组

的位置使用Integer数组
int[] orbitalBodies = {R.drawable.dres, R.drawable.duna, R.drawable.eeloo, R.drawable.eve, R.drawable.jool, R.drawable.kerbin, R.drawable.kerbol, R.drawable.moho};
int planetId = getIntent.getExtras().getInt("intOrbitalId");

if(planetId != null) {
    ImageView img = (ImageView)findViewById(R.id.image);
    img.setImageResource(orbitalBodies[planetId]);
}

由于

public static final class drawable 
{
        public static final int ic_launcher=0x7f020000;
}

答案 1 :(得分:0)

以这种方式试试......

img.setImageDrawable(getResources().getDrawable(orbitalBodies[planetId]));