Is there a simple way to get the user’s selection (the string value) from a spinner ? I am trying to avoid setting a listener on it and writing an onItemSelected() method, because I don’t need anything to happen when the user makes the selection. Rather, I’m trying to set up a button click to capture the selection and send it in a bundle to another activity. My spinner is being filled by a cursor. Here is my code, and it crashes on the line:
String choice = this.adapter.getItem(index).toString();
The code:
public class MainActivity extends BaseActivity
{
static final String TAG = "MainActivity";
static final String[] FROM = {CreateDB.C_CATEGORY};
static final int[] TO = {android.R.id.text1};
CreateDB dbBuilder;
SQLiteDatabase database;
Cursor cursor;
SimpleCursorAdapter adapter;
Spinner spinnerLocal;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbBuilder = new CreateDB(this);
database = dbBuilder.getReadableDatabase();
cursor = database.query(CreateDB.TABLE, null, null, null, null, null, CreateDB.C_CATEGORY + " DESC");
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, FROM, TO);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinnerRemote = (Spinner) findViewById(R.id.spinner2);
spinnerRemote.setAdapter(adapter);
}
public void createReview(View view)
{
//createReview runs when a button is clicked
Spinner spinner = (Spinner)findViewById(R.id.spinner2);
int index = spinner.getSelectedItemPosition();
String choice = this.adapter.getItem(index).toString();
Intent postReview = new Intent(this,Post.class);
Bundle bundle = new Bundle();
bundle.putString("CATEGORY", choice);
postReview.putExtras(bundle);
startActivity(postReview);
}
You don’t have a “string value”.
You used a
SimpleCursorAdapter. Your “value”, therefore, is aCursor.You can call
getSelectedItem()on theSpinner, which (for aCursorAdapter-backedSpinner) should return aCursorpositioned on the selected row. From there, read out whatever values you want viagetString()and kin.