Steve Gazzo Steve Gazzo - 1 month ago 4
Android Question

setImageResource to an array of drawables throws nullpointer exception

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
}


In debug I was able to confirm that orbitalBodies[planetId] returns the correct integer value for the drawables. I can't get past this little problem

Answer

use an Int array in the place of an Integer array

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]);
}

Because

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