简体   繁体   English

EditText留空时出错

[英]Errors when EditText left blank

Can anyone take a look at the below code and point out the obvious on what's wrong? 谁能看看下面的代码,指出明显的问题所在吗? The program gives an error when editText is left blank and only does the calculation once all the information is present. editText留为空白时,程序将给出错误,并且仅在所有信息都存在后才进行计算。 Currently the program crashes when there is text missing, why is this? 当前,当缺少文本时,程序崩溃,这是为什么?

EditText editText1, editText2;
double numA, numB, numC;
TextView answer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calc);

    editText1 = (EditText) findViewById(R.id.editText1);
    editText2 = (EditText) findViewById(R.id.editText2);
}

public void btnClick(View v)
{
    if(editText1.getText().length()==0)
    {
        editText1.setError("please input text"); 
    }{
        if  (editText2.getText().length()==0)
            {
                editText2.setError("please input text");
            }

    numA = new Double(editText1.getText().toString());
    numB = new Double(editText2.getText().toString());

    numC=(numA + numB); answer.setText(Double.toString(numC));
    }
}}

Change your code to this: 将代码更改为此:

if(TextUtils.isEmpty(editText1.getText()))
{
    editText1.setError("please input text"); 
}
if(TextUtils.isEmpty(editText2.getText()))
{
    editText2.setError("please input text"); 
}

What TextUtils.isEmpty(str) does is return str == null || str.length() == 0 TextUtils.isEmpty(str)作用是返回str == null || str.length() == 0 str == null || str.length() == 0 . str == null || str.length() == 0

The problem is that you're trying to parse "" into a number (a double, specifically). 问题是您正在尝试将""解析为数字(特别是双精度)。 You are checking for empty values, but you're still attempting to parse it even if you set the error. 您正在检查空值,但是即使设置了错误,您仍在尝试解析它。 You need to place the new Double() statements in a try-catch block, and catch the exceptions that happen when trying to parse an invalid input. 您需要将new Double()语句放置在try-catch块中,并捕获尝试解析无效输入时发生的异常。 This way, it's safe even if the user inputs a random string of text that is also not parseable as a double. 这样,即使用户输入了也不能解析为double的随机文本字符串,也是安全的。

Try this, 尝试这个,

Just Replace your statement with these..and it will work. 只需用这些替换您的声明即可。

if ((editText1.getText().toString()).equals(null))


if ((editText2.getText().toString()).equals(null))

Just Do 做就是了

if(editText1.getText().toString().equals(null){//your code here}
if(editText2.getText().toString().equals(null){//your code here}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM