java如何解决安卓中的空指针异常?
这是安卓系统中的一个简单应用。它在执行时显示nullpointerexception
。
我无法从edittext
中获取值。这里我只想从edittext
中获取值。
但它显示了nullpointerexception
如何解决这个问题
public class Calci extends Activity {
Button add;
String str1;
String str2;
EditText txt1;
EditText txt2;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calci);
add=(Button) findViewById(R.id.button1);
txt1=(EditText) findViewById(R.id.editText1);
str1=txt1.getText().toString();
txt2=(EditText) findViewById(R.id.editText2);
str2=txt2.getText().toString();
tv=(TextView) findViewById(R.id.textView4);
addition();
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addition();
}
});
}
private void addition(){
int res=0;
res=Integer.parseInt(str1)+Integer.parseInt(str2);
tv.setText(String.valueOf(res));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_calci, menu);
return true;
}
}
# 1 楼答案
只需替换oncreate()中的additiion()方法,并按如下所示更改该方法
# 2 楼答案
此处不调用addition()方法:
# 3 楼答案
确保在xml中为
editText1
和editText2
设置默认值,或者如果要访问用户输入的值,请将代码更改为,并在setOnClickListener之前删除addition():# 4 楼答案
只需从
onCreate()
中删除addition();
。就像我怀疑它第一次叫你的EditTexts
是空的一样另外,当调用
addition()
方法时,必须从两个EditTexts
中获取文本你的方法是