-6

I have an android application and I have two EditTexts.

The user inputs 'distance' and 'time.

I made an if statement to show an error message if the user didn't filled one of the two inputs:

String strDistance,strTime;
strDistance=edtDistance.getText().toString();
strTime=edtTime.getText().toString();
if(strDistance==null||strTime==null){
    txtError.setText("Please insert the distance and time");
}
else{
    calculateLogic();
    app.setFare(fare);
    Intent intent=new Intent(MainActivity.this,Fare.class);
    startActivity(intent);
}

It works fine if I filled the two inputs.

But when I fill only one of them, the application stops working (I don't get my error message)...

shkschneider
  • 17,833
  • 13
  • 59
  • 112

4 Answers4

1

Try following this one:-

if(strDistance.equals("")||strTime.equals("") {
 txtError.setText("Please insert the distance and time");
}
Dharma
  • 3,007
  • 3
  • 23
  • 38
Bhuvnesh
  • 1,055
  • 9
  • 29
0
 strDistance.gettext()

will never returns null.

 strDistance.isEmpty()

Use this

Ankit Kumar
  • 3,663
  • 2
  • 26
  • 38
0

Try trimming the result and using String.isEmpty(); This will ensure the text has a length of at least some text.

The reason to use isEmpty() is because EditText.getText() will never return null in its current implementation.

...
strDistance=edtDistance.getText().toString().trim();
strTime=edtTime.getText().toString().trim();

if(strDistance.isEmpty() || strTime.isEmpty()){
...
Numan1617
  • 1,158
  • 5
  • 19
0
Try this...

String strDistance,strTime;
strDistance=edtDistance.getText().toString();
strTime=edtTime.getText().toString();
if(strDistance.trim().isEmpty || strTime.trim().isEmpty()){
    Toast.makeText(getApplicationContext,"Please insert the distance and time",2000).show();
}
else{
    calculateLogic();
    app.setFare(fare);
    Intent intent=new Intent(MainActivity.this,Fare.class);
    startActivity(intent);
}