Issue with empty EditText

こ雲淡風輕ζ 提交于 2019-11-29 15:53:22

You just need to do a check on what the user has typed:

String input = editText.getText().toString();

if(input == null || input.trim().equals("")){
      Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}

EDIT

If you have a float, you have to do the check before you parse the float:

String input = editText.getText().toString();

if(input == null || input.trim().equals("")){
      // Toast message
      return;
}
float num1 = Float.parseFloat(input);

or

try{

   float num1 = Float.parseFloat(numA.getText().toString());

} catch (NumberFormatException e) {
   // Toast message - you cannot get a float from that input
   return;
}

You need to make sure that the EditText isn't empty. Try using something like:

EditText editText = (EditText) findViewById(R.id.edittext);
String text = editText.getText().toString();
if (text == null || text.equals("")) {
    Toast.makeText(this, "You did not enter a number", Toast.LENGTH_SHORT).show();
    return;
}

Pretty simple. Before you start calculations you should call the following code:

if (editText.getText().length() > 0) {
    // do the calculations
}

This way you'll know whether there is something in your EditText or not. If it's empty you can show an AlertDialog or a Toast to help your users. Hope this helps.

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