Search code examples
androidspinneronitemclick

Use selected item from Spinner in conditional Operation (if statement)


Please, I have two spinners. I am trying to get string values from spinnerA and then, to use these values as condition for display other values from spinnerB. I get these values from the database (mySql). A part of the code is below. The syntax is correct (Android Studio doesn't show any error), but nothing happen when I run it on the emulator I mean, the Toast doesn't show.

Any idea of the issue OR of the simplest way to do that please ?

PS : the Toast here is just to check if the value is stored.

public class ReviewActivity extends AppCompatActivity {

Spinner sp1, sp2;
TextView companyName;
Toolbar toolbar;

ArrayList<String> trajets = new ArrayList<String>();
ArrayList<String> horaires = new ArrayList<String>();

ArrayAdapter<String> adapter1, adapter2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_review);

    sp1 = (Spinner) findViewById(R.id.spinner_trajet);
    sp2 = (Spinner) findViewById(R.id.spinner_horaire);

    adapter1=new ArrayAdapter<String>(this,R.layout.travel_spinner_layout,R.id.txt,trajets);
    sp1.setAdapter(adapter1);

    sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
               String travel = sp1.getSelectedItem().toString();
               if (travel == "NY - CA") {
                    Toast.makeText(ReviewActivity.this, "Yaounde - Douala", Toast.LENGTH_LONG).show();
                } else if (travel == "CA - NY") {
                    Toast.makeText(ReviewActivity.this, "Douala - Yaounde", Toast.LENGTH_LONG).show();
                }
            }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {}

    });

Solution

  • Try, this change your == to equals() in

    itemSelectedListener

    see the changes below -:

    String travel = sp1.getSelectedItem().toString();
               if (travel.equals("NY - CA")) {
                    Toast.makeText(ReviewActivity.this, "Yaounde - Douala", Toast.LENGTH_LONG).show();
                } else if (travel.equals("CA - NY")) {
                    Toast.makeText(ReviewActivity.this, "Douala - Yaounde", Toast.LENGTH_LONG).show();
                }
    

    The “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

    and

    The equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal

    Here you can read what is difference between == and equals() in java.