【问题标题】:How can I check if edittext is empty?如何检查edittext是否为空?
【发布时间】:2020-05-29 14:04:36
【问题描述】:

我有两个编辑文本和一个计算按钮。我将输入两个数字,当我单击计算按钮时,我想将这两个数字相加。然后,当我单击该按钮时,我想通过 bundle 将这个结果显示在另一个活动中。但是,如果这些编辑文本为空,则会出现此应用停止等错误。我该如何解决这些问题?谢谢...

float number1,number2;
 float resultNet;

                Bundle  bundle = new Bundle(); 
                number1 = Float.parseFloat(edittext1.getText().toString());
                number2 = Float.parseFloat(edittext2.getText().toString());


if((!"".equals(edittext1)) && (!"".equals(edittext2)))
                {
                   // result = number1 - number2/4;
                    //bundle.putFloat("resultNet",resultnet); 


                    Intent intent = new Intent(Calculations.this,CalculationsResults.class);
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
                else 
                {
                    resultNet = number1 - number2/4;
                    bundle.putFloat("resultNet",resultnet); 


                    Intent intent = new Intent(Calculations.this,CalculationsResults.class);
                    intent.putExtras(bundle);
                    startActivity(intent);



                }

resultCalculation = findViewById(R.id.result);
Bundle bundle = getIntent().getExtras();
       float resultNet = bundle.getFloat("resultNet");
 if(bundle!= null)
        {

            resultCalculation.setText("Sum Result:"+ resultNet);



        }

【问题讨论】:

  • 想想edittext1是什么类型。
  • 所有编辑文本都是浮动的。
  • 这毫无意义。 a) 您不能将 Stringfloat 进行比较并期望它相等,并且 b) 浮点数不能为空。请说明您如何声明edittext1 和 2
  • 您的编辑显示edittext 不是float。如果文本为空导致崩溃,Float.parseFloat 也会抛出 NumberFormatException

标签: java android android-intent android-edittext bundle


【解决方案1】:

您应该检查 EditText 中文本的值,然后在您知道它们合适时使用这些值:

// Get the value of the text within the EditText
String enteredText1 = myEditText1.getText().toString();
String enteredText2 = myEditText2.getText().toString();

// Use String comparison to check if the text isn't empty
if(!enteredText1.equals("") && !enteredText2.equals(""){
    // Now you know the values aren't empty
    float myVal = Float.parseFloat(enteredText1);
    float myVal2 = Float.parseFloat(enteredText2);

    // do something with the values ...
}else{
    // do something when the values are empty ...
}

【讨论】:

    【解决方案2】:
    EditText textA = (EditText) findViewById(R.id.text1);
    EditText textB = (EditText) findViewById(R.id.text2);
    
    String fieldText1 = textA.getText().toString();
    String fieldText2 = textB.getText().toString();
    
    if (fieldText1.matches("") || fieldText2.matches("")) {
        Toast.makeText(this, "Please, Fill in all fields", Toast.LENGTH_SHORT).show();
    return;
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 2018-04-02
      • 2016-04-05
      • 2018-01-08
      相关资源
      最近更新 更多