我有這個 NullPointerException 我無法擺脫,我可以使用一些幫助,請:)所以我的第一個活動中有一個按鈕,應該將我發送到第二個活動(問題所在),但是當我單擊該按鈕時,我的活動崩潰并顯示此錯誤。當我單獨嘗試我的第二個活動時,它工作正常,但是當我附加我的 2 個項目時,錯誤彈出。這是錯誤:Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference這是我的代碼:public class entery_names extends AppCompatActivity {RelativeLayout layout;RelativeLayout.LayoutParams params;Button mBtn_add_et = null;int id;int i;static int previousid;@SuppressLint("NewApi")@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Submit = (Button)loginDialog.findViewById(R.id.Submit); mBtn_add_et = findViewById(R.id.btn_add_et); mBtn_add_et.setOnClickListener(new View.OnClickListener() { // this line is the problem apparently @Override public void onClick(View view) { if (id <= 4) { EditText et = new EditText(entery_names.this); id = View.generateViewId(); et.setId(id); layout = findViewById(R.id.relativeLayout); params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.BELOW, id); if (previousid == 0) params.addRule(RelativeLayout.BELOW, R.id.et3); else params.addRule(RelativeLayout.BELOW, previousid); previousid = et.getId(); et.setHint("Enter Name"); et.setHintTextColor(getResources().getColor(R.color.colorTransparentWhite)); et.setTextColor(getResources().getColor(R.color.colorTransparentWhite)); et.setX(findViewById(R.id.et1).getX()); layout.addView(et, params); } } });}}謝謝!
2 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
這一行:
mBtn_add_et = findViewById(R.id.btn_add_et);
產生一個空值。所以問題可能是:
1) 沒有Button
with id btn_add_et
in activity_main
,或者
2) 你為你的活動夸大了錯誤的布局setContentView(R.layout.activity_main);

青春有我
TA貢獻1784條經驗 獲得超8個贊
下面幾行是這里的罪魁禍首
mBtn_add_et = findViewById(R.id.btn_add_et);
mBtn_add_et.setOnClickListener
mBtn_add_et
為空,檢查findViewById是否實際返回一個對象。
添加回答
舉報
0/150
提交
取消