所以,我的代码给我带来了以下错误
01-30 15:30:09.658: E/AndroidRuntime(8705): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gameproj/com.example.gameproj.InvScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.addView(android.view.View)' on a null object reference
它说它在
行((RelativeLayout) findViewById(R.layout.activity_inv_screen)).addView(sv);
我不确定如何修复它。
以下是相关代码。
Protag hero = MainActivity.hero;
ArrayList<ItemBase> invn;
ArrayList<Button> bt;
int i = 0;
int j = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inv_screen);
setScreen();
}
public void setScreen(){
RelativeLayout rl = (RelativeLayout) findViewById(R.layout.activity_inv_screen);
RelativeLayout layout = new RelativeLayout(this);
HashMap<String, ArrayList<ItemBase>> items = hero.getStuff();
ScrollView sv = new ScrollView(this);
for (Entry<String, ArrayList<ItemBase>> entry : items.entrySet()){
String key = entry.getKey();
ArrayList<ItemBase> value = entry.getValue();
for (ItemBase item: value){
bt.add(new Button(this));
bt.get(i).setText(key);
layout.addView(bt.get(i));
invn.add(item);
bt.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
j = i;
}
});
i++;
}
}
((RelativeLayout) findViewById(R.layout.activity_inv_screen)).addView(sv);
sv.addView(layout);
}
答案 0 :(得分:1)
两次更改
更改
RelativeLayout rl = (RelativeLayout) findViewById(R.layout.activity_inv_screen);
到
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_inv_screen); // use its id not layout
然后改变
((RelativeLayout) findViewById(R.layout.activity_inv_screen)).addView(sv);
到
rl.addView(sv);