如何检查edittext是否为空?

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

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

  1. float number1,number2;
  2. float resultNet;
  3. Bundle bundle = new Bundle();
  4. number1 = Float.parseFloat(edittext1.getText().toString());
  5. number2 = Float.parseFloat(edittext2.getText().toString());
  6. if((!"".equals(edittext1)) && (!"".equals(edittext2)))
  7. {
  8. // result = number1 - number2/4;
  9. //bundle.putFloat("resultNet",resultnet);
  10. Intent intent = new Intent(Calculations.this,CalculationsResults.class);
  11. intent.putExtras(bundle);
  12. startActivity(intent);
  13. }
  14. else
  15. {
  16. resultNet = number1 - number2/4;
  17. bundle.putFloat("resultNet",resultnet);
  18. Intent intent = new Intent(Calculations.this,CalculationsResults.class);
  19. intent.putExtras(bundle);
  20. startActivity(intent);
  21. }
  1. resultCalculation = findViewById(R.id.result);
  2. Bundle bundle = getIntent().getExtras();
  3. float resultNet = bundle.getFloat("resultNet");
  4. if(bundle!= null)
  5. {
  6. resultCalculation.setText("Sum Result:"+ resultNet);
  7. }
mrwjdhj3

mrwjdhj31#

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

  1. // Get the value of the text within the EditText
  2. String enteredText1 = myEditText1.getText().toString();
  3. String enteredText2 = myEditText2.getText().toString();
  4. // Use String comparison to check if the text isn't empty
  5. if(!enteredText1.equals("") && !enteredText2.equals(""){
  6. // Now you know the values aren't empty
  7. float myVal = Float.parseFloat(enteredText1);
  8. float myVal2 = Float.parseFloat(enteredText2);
  9. // do something with the values ...
  10. }else{
  11. // do something when the values are empty ...
  12. }
rslzwgfq

rslzwgfq2#

  1. EditText textA = (EditText) findViewById(R.id.text1);
  2. EditText textB = (EditText) findViewById(R.id.text2);
  3. String fieldText1 = textA.getText().toString();
  4. String fieldText2 = textB.getText().toString();
  5. if (fieldText1.matches("") || fieldText2.matches("")) {
  6. Toast.makeText(this, "Please, Fill in all fields", Toast.LENGTH_SHORT).show();
  7. return;
  8. }

相关问题