-2

I'm working on android studio but this is command but this error

Error:(27, 12) error: non-static method setOnItemSelectedListener(OnItemSelectedListener) cannot be referenced from a static context

I don't know how to fix this error

package com.example.toshiba.mystudy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class FirstActivity extends Activity  {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.semester_array,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        //spinner.setOnItemSelectedListener(this);

        Spinner.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                parent.getItemAtPosition(position);
                Intent intent = null;
                switch(position) {
                    case 1:
                        intent = new Intent(FirstActivity.this, SecondActivity.class);
                        break;
                    //case2:
                        // intent = new Intent(FirstActivity.this, TargetActivity2.class);
                        // break;// }
                } 
                startActivity(intent);
            }       
            public void onNothingSelected(AdapterView<?> parent) {

            }
        );
    }

}
Arkar Aung
  • 3,554
  • 1
  • 16
  • 25
marwa
  • 5
  • 1
  • 3

2 Answers2

2

Do like

spinner.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() {

Assign setOnItemSelectedListener to spinner(object of Spinner).

not an Spinner(View directly)

M D
  • 47,665
  • 9
  • 93
  • 114
0

Use this code to assign setOnItemSelectedListener method to your spinner.

spinner.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    parent.getItemAtPosition(position);
     Intent intent = null;
    switch(position){
        case 1:
            intent = new Intent(FirstActivity.this, SecondActivity.class);
            break;
       //case2:
         // intent = new Intent(FirstActivity.this, TargetActivity2.class);
         // break;// }
 } startActivity(intent);
}
public void onNothingSelected(AdapterView<?> parent){

        }

});
Prashant Bhoir
  • 900
  • 6
  • 8