我有第二個類調用Main類的方法,此方法將設置一個TextView
與一個數字,但該應用程序崩潰,因爲nullPointerException
爲findViewById()
。我相信問題是當findViewById
被另一個類調用時,它會查找調用類的setContentView()
中的視圖。爲特定佈局調用findViewById()? NullPointerException on findViewById()
那麼如何指定哪個佈局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;
這是什麼?它是片段嗎?活動? –
同時添加活動xml ..你可以直接傳遞Textview obj,你可以直接使用該obj設置而不是findViewById() – Manmohan
這段代碼有很多錯誤,但最重要的是,你嘗試使用的方法是隻是明顯錯誤。您需要回顧Android的基礎知識。一個Activity可以通過多種方式更新另一個。首先閱讀'Interace'和'startActivityForResult()'..你不應該把活動看作POJO。 – Simon