1

I am creating an android spinner. It is displaying properly but nothing happens on selecting an option. Why is 'if' command not working?

public class Main2Activity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    spinner= (Spinner) findViewById(R.id.spinner);
    adapter=ArrayAdapter.createFromResource(this,R.array.spinner,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {//why 'if' command is not working?
            if(adapterView.getItemAtPosition(i).toString().equals("Question 1"))
            {
                Intent intent=new Intent(Main2Activity.this,Main2Activity.class);
            }
            if(adapterView.getItemAtPosition(i).toString().equals("Question 2"))
            {
                Intent intent=new Intent(Main2Activity.this,main3Activity.class);
            }

        }

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

        }
    });`
  • Have you tried debugging to see what `adapterView.getItemAtPosition(i)` is returning? It would be clearer and better to use `adapter.get(i).toString().equals("Question 1")`. Or if you know the order of the items, just `if (i == 0)` for question 1 and `if (i == 1)` for question 2. – Felix Guo Aug 04 '17 at 21:42

1 Answers1

0

You are not starting the activity with intent. Do this:

        startActivity(intent);

After intent declaration and assignment in both if and else.

Kavach Chandra
  • 770
  • 1
  • 10
  • 25
  • Hey, if you feel an answer solved the problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on older SO which still don't have answers. – Kavach Chandra Aug 04 '17 at 21:46
  • Thanks! I forgot that one. –  Aug 04 '17 at 22:03