如何检查edittext是否为空?

zpgglvta  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(357)

我有两个编辑文本和一个计算按钮。我将输入两个数字,当我单击“计算”按钮时,我希望将这两个数字相加。然后,当我单击该按钮时,我希望通过bundle在另一个活动中显示此结果。但是,如果这些editText是空的,我会出现一个错误,比如这个应用程序停止了。我怎样才能解决这些问题?谢谢您。。。

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

        }
mrwjdhj3

mrwjdhj31#

您应该检查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 ...
}
rslzwgfq

rslzwgfq2#

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

相关问题