I have two edittexts and a calculate button. I will enter two numbers and I want to sum these two numbers when I click on the calculate button.Then, when I click on the button, I want to show this result in another activity through bundle. However, if these edittexts are empty, I take a error such as this app stopped. How can I solve these problem? Thank you ...
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);
}
You should check the value of the text inside of the EditText then use the values when you know they're appropriate:
// 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.