问题
public void add(View v)
{
EditText first=findViewById(R.id.first),second=findViewById(R.id.second);
double f=Double.parseDouble(first.getText().toString());
double s=Double.parseDouble(second.getText().toString());
TextView result=findViewById(R.id.result);
double r;
if(TextUtils.isEmpty(first.getText().toString()))
{
first.setError("This field can't be empty");
}
else if(TextUtils.isEmpty(second.getText().toString()))
{
second.setError("This field can't be empty");
}
else {
r = f + s;
result.setText("" + r);
}
}
I want to add two numbers from taking input from user and display an error msg if editText is empty.
But on executing this piece of code my app keeps crashing.
回答1:
You need convert your Editext value in to Double if Editext value is not empty
Try this
public void add(View v)
{
EditText first=findViewById(R.id.first);
EditText second=findViewById(R.id.second);
TextView result=findViewById(R.id.result);
double r;
if(TextUtils.isEmpty(first.getText().toString()))
{
first.setError("This field can't be empty");
}
else if(TextUtils.isEmpty(second.getText().toString()))
{
second.setError("This field can't be empty");
}
else {
double s=Double.parseDouble(second.getText().toString());
double f=Double.parseDouble(first.getText().toString());
r = f + s;
result.setText("" + r);
}
}
回答2:
- Add "null" check ,before the empty check
eg :
if((first.gettext().toString) == null ||
TextUtils.isEmpty(first.getText().toString()))
{
first.setError("This field can't be empty");
}
else if((second.gettext().toString) == null || TextUtils.isEmpty(second.getText().toString()))
{
second.setError("This field can't be empty");
}
else {
r = f + s;
result.setText("" + r);
}
回答3:
Declare first,second globally
public void add(View v) {
first = findViewById(R.id.first);
second = findViewById(R.id.second);
TextView result = findViewById(R.id.result);
double r;
if (Validates()) {
double s = Double.parseDouble(second.getText().toString());
double f = Double.parseDouble(first.getText().toString());
r = f + s;
result.setText("" + r);
}
}
public boolean Validates() {
if (first.getText().toString().equalsIgnoreCase("")) {
first.setError("This field can't be empty");
return false;
} else if (second.getText().toString().equalsIgnoreCase("")) {
second.setError("This field can't be empty");
return false;
} else {
return true;
}
}
来源:https://stackoverflow.com/questions/49974963/want-to-display-an-error-message-if-the-value-is-null-or-void-if-edittext-is-emp