Israt Israt - 28 days ago 5
Java Question

List view activity is not working properly in switch case inside spinner class

Here BookList.java is a spinner class which maintains two occurrences one is book and another author and both have their own list view class. Through switching cases inside OnItemSelected() method their intent is accessed. But the problem i'm facing is that the first list view applied intent which is for book can't be accessed but can access author intent. it would be helpful if anybody help me editing my code. Here goes the java file.

public class BookList extends Activity implements OnItemSelectedListener {

Spinner spinner;
//private static final String[]paths = {"Book", "Author"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booklist);
TextView t =(TextView)findViewById(R.id.t1) ;
spinner = (Spinner)findViewById(R.id.spinner);
//ArrayAdapter<String>adapter = new ArrayAdapter<String>(BookList.this,
//android.R.layout.simple_spinner_item,paths);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.blist_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(this);

}

public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {

final Intent intent;
switch (position) {
case 1:
intent = new Intent(BookList.this, BookListView.class);
startActivity(intent);
break;
case 2:
intent = new Intent(BookList.this, BookListAuthorView.class);
startActivity(intent);
break;
}



}
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(this, "Please choose a field", Toast.LENGTH_SHORT).show();

}


}

Answer

the item positions starts from 0 not from 1 so use this

And so 0 position will automatically trigger first time you open your activity so create a spinner array something like this for spinner

String arr ={"select choice","book","author"};

                switch (position) {
                    case 1:
                        intent = new Intent(BookList.this, BookListView.class);
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(BookList.this, BookListAuthorView.class);
                        startActivity(intent);
                        break;
                }

plus you don't have to call `adapter.notifyDataSetChanged();'