我有两个edittext和一个calculate按钮。我将输入两个数字,并单击``计算''按钮时要对这两个数字求和。然后,当我单击按钮时,我想通过捆绑销售在另一个活动中显示此结果。但是,如果这些edittexts为空,则会出现错误,例如此应用程序已停止。我该如何解决这些问题?谢谢...
float number1,number2;
float resultNet;
Bundle bundle = new Bundle();
number1 = Float.parseFloat(edittext1.getText().toString());
number2 = Float.parseFloat(edittext2.getText().toString());
if((!"".equals(edittext1)) && (!"".equals(edittext2)))
{
// result = number1 - number2/4;
//bundle.putFloat("resultNet",resultnet);
Intent intent = new Intent(Calculations.this,CalculationsResults.class);
intent.putExtras(bundle);
startActivity(intent);
}
else
{
resultNet = number1 - number2/4;
bundle.putFloat("resultNet",resultnet);
Intent intent = new Intent(Calculations.this,CalculationsResults.class);
intent.putExtras(bundle);
startActivity(intent);
}
resultCalculation = findViewById(R.id.result);
Bundle bundle = getIntent().getExtras();
float resultNet = bundle.getFloat("resultNet");
if(bundle!= null)
{
resultCalculation.setText("Sum Result:"+ resultNet);
}
您应该检查EditText内文本的值,然后在知道合适的情况下使用这些值:
// Get the value of the text within the EditText
String enteredText1 = myEditText1.getText().toString();
String enteredText2 = myEditText2.getText().toString();
// Use String comparison to check if the text isn't empty
if(!enteredText1.equals("") && !enteredText2.equals(""){
// Now you know the values aren't empty
float myVal = Float.parseFloat(enteredText1);
float myVal2 = Float.parseFloat(enteredText2);
// do something with the values ...
}else{
// do something when the values are empty ...
}
EditText textA = (EditText) findViewById(R.id.text1);
EditText textB = (EditText) findViewById(R.id.text2);
String fieldText1 = textA.getText().toString();
String fieldText2 = textB.getText().toString();
if (fieldText1.matches("") || fieldText2.matches("")) {
Toast.makeText(this, "Please, Fill in all fields", Toast.LENGTH_SHORT).show();
return;
}