Android, Validate an empty EditText field

匆匆过客 提交于 2019-12-13 06:25:46

问题


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

}


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/20184128/android-validate-an-empty-edittext-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!