我有這個(gè) NullPointerException 我無法擺脫,我可以使用一些幫助,請(qǐng):)所以我的第一個(gè)活動(dòng)中有一個(gè)按鈕,應(yīng)該將我發(fā)送到第二個(gè)活動(dòng)(問題所在),但是當(dāng)我單擊該按鈕時(shí),我的活動(dòng)崩潰并顯示此錯(cuò)誤。當(dāng)我單獨(dú)嘗試我的第二個(gè)活動(dòng)時(shí),它工作正常,但是當(dāng)我附加我的 2 個(gè)項(xiàng)目時(shí),錯(cuò)誤彈出。這是錯(cuò)誤: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貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
這一行:
mBtn_add_et = findViewById(R.id.btn_add_et);
產(chǎn)生一個(gè)空值。所以問題可能是:
1) 沒有Button
with id btn_add_et
in activity_main
,或者
2) 你為你的活動(dòng)夸大了錯(cuò)誤的布局setContentView(R.layout.activity_main);

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面幾行是這里的罪魁禍?zhǔn)?/p>
mBtn_add_et = findViewById(R.id.btn_add_et);
mBtn_add_et.setOnClickListener
mBtn_add_et
為空,檢查findViewById是否實(shí)際返回一個(gè)對(duì)象。
添加回答
舉報(bào)
0/150
提交
取消