Search code examples
javaandroidandroid-spinner

Get spinner selected item and passing data


What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.

UPDATE:

I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.

So this is my code for 1st activity, I will just put only one first :

btnAsia.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
            intent.putExtra("continent", "asia");
            startActivity(intent);
        }
    });

This is the string array in strings.xml:

<string-array name="asia">
    <item>Japan</item>
    <item>Thailand</item>
    <item>Vietnam</item>
    <item>South Korea</item>
</string-array>

and this is the code in 2nd activity:

private void DestinationSpinner()
{
    Bundle bundle=getIntent().getExtras();
    if(bundle!=null) {
        String continent = bundle.getString("continent");
        switch (continent) {
            case "asia":
                ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item);  // Create an ArrayAdapter using the string array and a default spinner layout
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
                spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
                break;  }

and lastly this is the code for retrieve selected item from spinner:

public void AvailableAirlines()
{
    spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selected=spinnerDestination.getItemAtPosition(position).toString();

            if (continent.equals("asia") && selected.equals("Japan"))
            {
                availableAirlines.setText("Available airports");
            }
        }

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

        }
    });
}

and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.


Solution

  • I think the issue is this line if(selected=="Japan")

    In Java you will need to use equals instead of the == operator.

    The == checks if the two pointers are pointing to the same memory location. Equals will compare their content.