Reputation: 156
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.
Upvotes: 1
Views: 1090
Reputation: 1219
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;
}
}
Upvotes: 1
Reputation: 168
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);
}
Upvotes: 1
Reputation: 9732
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);
}
}
Upvotes: 3