Hi I have a simple temperature converter application where the application crashes whenever the field is empty. I tried some validation I found on S.O but it keeps crashing, so can anyone help me to validate and empty field where it would give a dialogue like a Toast saying "Field cannot be empty". Thank you.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText celsiusEdit = (EditText) findViewById(R.id.celsiusEdit);
final EditText farhEdit = (EditText) findViewById(R.id.farhEdit);
Button c2f, f2c;
c2f = (Button) findViewById(R.id.c2fButton);
f2c = (Button) findViewById(R.id.f2cButton);
c2f.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
double celsius = Double.valueOf(celsiusEdit.getText().toString());
if((double)celsiusEdit.getText().toString().trim().length() == 0){
celsiusEdit.setError("Cannot be empty");
}else{
double farh = (celsius -32) * 5/9;
farhEdit.setText(String.valueOf(farh));
}}
});
f2c.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
double farh = Double.valueOf(farhEdit.getText().toString());
double celsius = (farh * 9/5) + 32;
celsiusEdit.setText(String.valueOf(celsius));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Your if statement makes no sense, you should do something like this:
However you could run into an issue if a non-number is put into that textbox because
will throw a NumberFormatException, so you should put that in a try.
Try this
You can try and import this class here Android Form Validation Class
This can help you to validate the Form fields, just need to follow the instructions. (: