當我點擊按鈕來刪除一個TextView ,Button 和 LinearLayout.時,程序崩潰。下面是logcat輸出,當我想在118行刪除View時就崩潰了。
tasklayout.removeView(taskbutton);
04-15 14:35:58.222: E/AndroidRuntime(632): java.lang.NullPointerException
04-15 14:35:58.222: E/AndroidRuntime(632): at com.com.com.addtask.deltask(addtask.java:118)
04-15 14:35:58.222: E/AndroidRuntime(632): at com.com.com.addtask$2.onClick(addtask.java:65)
04-15 14:35:58.222: E/AndroidRuntime(632): at android.view.View.performClick(View.java:3511)
04-15 14:35:58.222: E/AndroidRuntime(632): at android.view.View$PerformClick.run(View.java:14105)
04-15 14:35:58.222: E/AndroidRuntime(632): at android.os.Handler.handleCallback(Handler.java:605)
onClickListner 和 deltask void
Button delt = (Button) findViewById(R.id.btndelete1);
delt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
deltask(v);
}
});
public void deltask(View v) {
SharedPreferences datatask;
datatask = getSharedPreferences(filename, 0);
int tnum = datatask.getInt("tasknumber", 1);
int layoutnum = 1000 + tnum;
int textviewnum = 1100 + tnum;
int buttonviewnum = 1200 + tnum;
LinearLayout layout = (LinearLayout) findViewById(R.id.taskll);
LinearLayout tasklayout = (LinearLayout) findViewById(layoutnum);
TextView tasktv = (TextView) findViewById(textviewnum);
Button taskbutton = (Button) findViewById(buttonviewnum);
tasklayout.removeView(taskbutton);
tasklayout.removeView(tasktv);
layout.removeView(tasklayout);
}
估計是tasklayout為空,而tasklayout的賦值語句似乎有問題:
LinearLayout tasklayout = (LinearLayout) findViewById(layoutnum);
這個layoutnum似乎是你計算出來的一個數字,不是一個正確的資源ID,找不到對應的Layout View,tasklayout為null,就會導致tasklayout.removeView(xx)報空指針錯。