-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,185
  • 13
  • 56
  • 110

5 Answers5

1

Try following this one:-

if(strDistance.equals("")||strTime.equals("") {
 txtError.setText("Please insert the distance and time");
}
Dharma
  • 2,965
  • 3
  • 20
  • 36
Rajat Sharma
  • 960
  • 9
  • 26
0

Try it it will help you

     strDistance.equals("") 

or you can check with

strDistance.isEmpty().
Tufan
  • 3,384
  • 4
  • 32
  • 53
0
 strDistance.gettext()

will never returns null.

 strDistance.isEmpty()

Use this

Ankit Kumar
  • 3,508
  • 2
  • 22
  • 36
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,148
  • 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);
}