我有一个Second类从Main类调用一个方法,这个方法会设置一个带有数字的TextView
,但由于nullPointerException
findViewById()
,应用程序崩溃了。我认为问题在于,当从另一个类调用findViewById
时,它将在调用类的setContentView()
中查找该视图。
那么如何指定哪个布局findViewById()
正在查看?
为什么会出现'nullPointerException'?
*************************************************
MAIN CLASS
*************************************************
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!NUMBER.exists()) {
new File("/data/data/com.app.clicker/files").mkdir();
writeInt(NUMBER, total = 0);
writeInt(CLICK, perClick = 1);
writeInt(CASH, $ = 500);
setView(R.id.numberView, "", readInt(NUMBER));
setView(R.id.perClickView, "Per Click ", readInt(CLICK));
setView(R.id.cash, "Cash ", readInt(CASH));
} else {
setView(R.id.perClickView, "Per Click ", readInt(CLICK));
setView(R.id.cash, "Cash ", readInt(CASH));
setView(R.id.numberView, "", readInt(NUMBER));
}
}
public void setTotal(int total) {
writeInt(NUMBER, total);
setView(R.id.numberView, "", this.total);
}
public void setView(int view, String writeBefore, int num) {
TextView textView = (TextView) findViewById(view); >> NullPointerException
textView.setText(writeBefore + Integer.toString(num));
}
************************************************
Second Class
************************************************
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev);
Main main = new Main();
total = main.getTotal();
perClick = main.getPerClick();
$ = main.get$();
devListView();
}
final EditText editTotal = new EditText(Dev.this);
final EditText editPerClick = new EditText(Dev.this);
final EditText edit$ = new EditText(Dev.this);
editTotal.setInputType(InputType.TYPE_CLASS_NUMBER);
editPerClick.setInputType(InputType.TYPE_CLASS_NUMBER);
edit$.setInputType(InputType.TYPE_CLASS_NUMBER);
switch (position) {
case 0:
Builder devTotal = new AlertDialog.Builder(Dev.this);
devTotal.setTitle("Set Total").setView(editTotal).setNeutralButton("Set", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
main.setTotal(Integer.parseInt(editTotal.getText().toString())); ************ Call to Main to SetTotal
}
});
devTotal.create().show();
break;
答案 0 :(得分:0)
从你的代码:
Main main = new Main();
看起来你正在通过调用new Main()
来创建活动(R.layout.activity_main),你不应该这样做:如果你想发送一些值,你可以用startActivity
开始活动他们使用Intent
额外内容。