2014-11-22 82 views
2
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的正确整数值。我不能让过去的这个小问题setImageResource到一个可绘制数组抛出空指针异常

+0

看起来'img'为空。 – 2014-11-22 08:10:18

+0

验证在view_orbital布局内存在R.id.image(ImageView)。 – MathanG 2014-11-22 08:50:44

+0

麦克M钉了它。我将img设置为布局文件中不存在的对象。从来没有我认为它会编译这个错误,所以我从来没有想过要检查它。 – 2014-11-23 03:24:51

回答

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; 
} 
0

试试这样...

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

任何理由,为什么这应该工作? (您的答案出现在低质量评论队列中) – 2014-11-22 08:59:21