Reputation: 1
I have a app for convert km/h for mph. If the form is blank and press button convert, the app simply closes. I understand that i need a function thats validade if the form is blank and show a message informating users that form cannot be blank but i cannot found a code for my problem.
My onClick code is:
buttonConverter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
double Value1 = Double.valueOf(txtKmhUser.getText().toString());
double Value2 = Value1 / 1.60;
Result.setText(String.valueOf(Value2));
}
});
Upvotes: -1
Views: 63
Reputation: 6717
You can show a toast, if the EditText
is empty.
@Override
public void onClick(View arg0) {
String yourString = txtKmhUser.getText().toString();
if(!yourString.equals("")){
double Value1 = Double.valueOf(yourString);
double Value2 = Value1 / 1.60;
Result.setText(String.valueOf(Value2));
}else{
Toast.makeText(this, "Form can not be blank", Toast.LENGTH_SHORT).show();
}
}
Upvotes: 1
Reputation: 225
Check your edit text has value null before converting it
if(!value1.equals(null))
Upvotes: 0
Reputation: 1012
The reason your app is crashing is because Double.valueOf("") throws a number format exception. So you need to validate your form ahead of processing or use a try/catch for the exception.
buttonConverter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if(txtQuilometros.getText().toString().length() > 0) {
double Value1 = Double.valueOf(txtQuilometros.getText().toString());
double Value2 = Value1 / 1.60;
Result.setText(String.valueOf(Value2));
} else {
txtQuilometros.setError("Please enter a value");
}
});
Upvotes: 0
Reputation: 4001
Just do validation before converting
buttonConverter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String str=txtQuilometros.getText().toString();
if(str.length()>0)
{
double Value1 = Double.valueOf(str);
double Value2 = Value1 / 1.60;
Result.setText(String.valueOf(Value2));
}
}
});
Upvotes: 0