Reputation: 149
I'm currently trying to add a condition based on what the user has selected on the drop down. If the first item is selected, then the data entered on the textView will be multiplied by 34, else the second item will be multiplied by 18. So far I can test the first selection works as it should, but it's not picking up the second selection. Could anybody explain to me the proper way to tackle this conditional? this is what my code looks like.
public class CatalinaFerryTickets extends AppCompatActivity{
String[] ferryRoutes = new String[]{"To Catalina Island", "To Long Beach"};
private Button renderBtn;
EditText handleData;
TextView displayData;
@Override
protected void onCreate(Bundle savedInstanceState) {
// RENDER SPINNER TO DEVICE
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalina_ferry_tickets);
final Spinner spin=findViewById(R.id.mySpinner);
final ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, ferryRoutes);
spin.setAdapter(myAdapter);
renderBtn=findViewById(R.id.button);
displayData=findViewById(R.id.textView);
displayData.setMovementMethod(new ScrollingMovementMethod());
renderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleData=findViewById(R.id.editInput);
int ticketAmount = Integer.parseInt(handleData.getText().toString());
int total;
// FAULTY CONDITIONAL STATEMENT
if (ferryRoutes[0] == "To Catalina Island"){
total = ticketAmount * 34;
displayData.setText(Integer.toString(total));
}
else{
total = ticketAmount * 18;
displayData.setText(Integer.toString(total));
}
}
});
}
}
Upvotes: 0
Views: 46
Reputation: 21124
The problem here is that the ferryRoutes
array is never linked to a drop-down component.
Because of that, the condition
if (ferryRoutes[0] == "To Catalina Island")
will always be true
, and the else
block will never be executed.
Also, never compare String
(s) using the reference equality operator (==
). Use equals
if ("To Catalina Island".equals(ferryRoutes[0]))
You might be lucky to have the String
(s) interned, and that would make the equality operator work. But don't do that as a general rule.
Upvotes: 1
Reputation: 93561
You aren't checking what's selected, you're checking what the value is in a static array. So it will always take one branch. If you want to do something based on the spinner selection, you need to actually query the spinner for what's selected.
Upvotes: 1