Reputation: 641
How can I check the below conditions in switch instead of if?
I want to check this conditions in switch case.
if(tvStartLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter start location", Toast.LENGTH_SHORT).show();
}
else if(tvEndLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter end location", Toast.LENGTH_SHORT).show();
}
else if(etStartOdometer.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Trip Start Odometer reading", Toast.LENGTH_SHORT).show();
}
else if(etEndOdometer.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Trip End Odometer reading", Toast.LENGTH_SHORT).show();
}
else if((compareOdometerReading(etStartOdometer.getText().toString(),etEndOdometer.getText().toString())) == -1)
{
Toast.makeText(getActivity(),"End Odometer reading should be greater than Start Odometer Reading (eOR > sOR)!", Toast.LENGTH_SHORT).show();
}
else if(etManifest.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Manifest", Toast.LENGTH_SHORT).show();
}
else if(etShipper.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Shipper", Toast.LENGTH_SHORT).show();
}
else if(etCommodity.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Commodity", Toast.LENGTH_SHORT).show();
}
Suggest Me Guys In Advance
Upvotes: 1
Views: 106
Reputation: 393841
You can't replace them with a switch statement, since each condition checks a different variable. You could replace them with a method, to avoid code duplication.
public boolean testControl (EditText control, String name) { // I'm assuming your control is an EditText
// (perhaps I got the type wrong)
if (control.getText().toString().equalsIgnoreCase("")) {
Toast.makeText(getActivity(),"Please enter " + name, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
You can call the method :
boolean hasValue = testControl (etShipper, "Shipper");
Then, if you store your EditText
controls in some array/Collection, you can call this method in a loop.
Upvotes: 0
Reputation: 1796
As others mentioned you are comparing multiple variables to a constant, and switch cannot do that. But you could improve code reuse and readability by putting all those variables in array or list and then iterating over them. For example something like this:
TextView[] toValidate = new TextView[]{tvStartLocation, tvEndLocation, etStartOdometer}; //etc
for(TextView tv : toValidate){
if(tv.getText().toString().equalsIgnoreCase(""))
{
//Display message..
}
}
Upvotes: 0
Reputation: 3045
In a switch statement you compare one variable against different constant values. You want to compare different variables against one constant value. This is not possible, and IMHO, does not make sense in your case.
Upvotes: 2