Android, Validate an empty EditText field

2019-09-19 06:54发布

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;
}

}

3条回答
虎瘦雄心在
2楼-- · 2019-09-19 07:21

Your if statement makes no sense, you should do something like this:

if(celsiusEdit.getText().toString().trim().length() == 0){

However you could run into an issue if a non-number is put into that textbox because

Double celsius =     Double.valueOf(celsiusEdit.getText().toString());

will throw a NumberFormatException, so you should put that in a try.

查看更多
可以哭但决不认输i
3楼-- · 2019-09-19 07:29

Try this

if (celsiusEdit.getText().toString().matches("")) {
    Toast.makeText(this, "Field cannot be empty", Toast.LENGTH_SHORT).show();
    return;
}else{
  double celsius = Double.valueOf(celsiusEdit.getText().toString());
  double farh = (celsius -32) * 5/9;

  farhEdit.setText(String.valueOf(farh));
}
查看更多
可以哭但决不认输i
4楼-- · 2019-09-19 07:39

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. (:

查看更多
登录 后发表回答