My android app is crashing due to two empty edittext fields

时间:2017-06-20 12:36:43

标签: android mobile

    @Override
    public void onClick(View v)

    {
        float Percentage, newPercentage = 0;
        int Number;
        EditText Total = (EditText) findViewById(R.id.editText3);
        EditText Done = (EditText) findViewById(R.id.editText4);

        float num1 = Float.parseFloat(Total.getText().toString());
        float num2 = Float.parseFloat(Done.getText().toString());




        Percentage = (num2 / num1) * 100;
}
}

Above is my code, when I leave any one of them empty, it crashes.How to get over it.

6 个答案:

答案 0 :(得分:1)

只需检查用户是否输入了任何内容,然后解析您的值:

if(!Total.getText().toString().matches(""))
    float num1 = Float.parseFloat(Total.getText().toString());

答案 1 :(得分:0)

试试这个

  button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
if(!Total.getText().toString().trim().equals("")&&!Done.getText().toString().trim().equals("")){
                 float num1 = Float.parseFloat(Total.getText().toString());
                float num2 = Float.parseFloat(Done.getText().toString());

             Percentage = (num2 / num1) * 100;}
            }
        });

答案 2 :(得分:0)

如果EditText不为空,则可以应用条件,然后您的代码就像那样运行

            float Percentage, newPercentage = 0;
            int Number;
            EditText Total = (EditText) findViewById(R.id.editText3);
            EditText Done = (EditText) findViewById(R.id.editText4);

            String total=Total.getText().toString();
            String done=Done.getText().toString();

            if (!total.isEmpty() && !done.isEmpty()) {

                float num1 = Float.parseFloat(Total.getText().toString());
                float num2 = Float.parseFloat(Done.getText().toString());


                Percentage = (num2 / num1) * 100;
            }else {
                Toast.makeText(OpenFile.this, "Fill values", Toast.LENGTH_SHORT).show();
            }

答案 3 :(得分:0)

尝试使用Try ... Catch

var number = 20;
for (var i = 1; i < number;i++)
{
    var result = i + " ";
    if (i % 3 == 0)
    {
        result += "Fizz";
    }
    if (i % 5 == 0)
    {
        result += "Buzz";
    }
    document.write(result+"<br>");
}

答案 4 :(得分:0)

首先检查是否正确找到editText 之后还检查isEmpty条件以避免NullPointer异常

if (!editText1.getText().toString().isEmpty() && !editText2.getText().toString().isEmpty()){
    float num1 = Float.parseFloat(Total.getText().toString());
    float num2 = Float.parseFloat(Done.getText().toString());
}

答案 5 :(得分:0)

检查空文本,如果不为空则执行计算

  if(!Total.getText().toString().isEmpty() && !Done.getText().toString().isEmpty()){
                 float num1 = Float.parseFloat(Total.getText().toString());
                float num2 = Float.parseFloat(Done.getText().toString());

             Percentage = (num2 / num1) * 100;}
            }
        });