应用程序停止当我在提供输入后单击“添加”按钮或任何其他按钮
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Buttons and Text Fields
private Button btnAdd,btnSub,btnDiv,btnMul;
private EditText etFirst,etSecond;
private TextView tvresult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init()
{
// Button Id's
btnAdd=(Button)findViewById(R.id.btnAdd);
btnSub=(Button)findViewById(R.id.btnSub);
btnMul=(Button)findViewById(R.id.btnMulti);
btnDiv=(Button)findViewById(R.id.btnDivide);
btnAdd.setOnClickListener(this);
btnSub.setOnClickListener(this);
btnDiv.setOnClickListener(this);
btnMul.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//Operations
String num1=etFirst.getText().toString();
String num2=etSecond.getText().toString();
switch(v.getId())
{
case R.id.btnAdd:
int addition=Integer.parseInt(num1)+Integer.parseInt(num2);
tvresult.setText(String.valueOf(addition));
break;
case R.id.btnSub:
int sub=Integer.parseInt(num1)-Integer.parseInt(num2);
tvresult.setText(String.valueOf(sub));
break;
case R.id.btnMulti:
int multiply=Integer.parseInt(num1)* Integer.parseInt(num2);
tvresult.setText(String.valueOf(multiply));
break;
case R.id.btnDivide:
int div = Integer.parseInt(num1) / Integer.parseInt(num2);
tvresult.setText(String.valueOf(div));
break;
}
}
}
答案 0 :(得分:0)
您尚未初始化etFirst
& etSecond
。
将其添加到您的init()
方法:
etFirst = (EditText) findViewById(R.id.etFirst);
etSecond = (EditText) findViewById(R.id.etSecond);