我有这个 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 回答
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
至尊宝的传说
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);
![?](http://img1.sycdn.imooc.com/545845d30001ee8a02200220-100-100.jpg)
青春有我
TA贡献1784条经验 获得超8个赞
下面几行是这里的罪魁祸首
mBtn_add_et = findViewById(R.id.btn_add_et);
mBtn_add_et.setOnClickListener
mBtn_add_et
为空,检查findViewById是否实际返回一个对象。
添加回答
举报
0/150
提交
取消