Monday, March 19, 2012

setSelection on Spinner based on rowId


http://stackoverflow.com/questions/2559611/setselection-on-spinner-based-on-rowid

If you want to set the selection of a Spinner thats backed by a CursorAdapter, you can loop through all the items in the Cursor and look for the one you want (assuming that the primary key in your table is named "_id"):
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new SimpleCursorAdapter(...));
for (int i = 0; i < spinner.getCount(); i++) {
    Cursor value = (Cursor) spinner.getItemAtPosition(i);
    long id = value.getLong(value.getColumnIndex("_id");
    if (id == rowid) {
        spinner.setSelection(i);
    }
}
If you want to get the rowid of a selected item, you can do something similar:
Cursor cursor = (Cursor) spinner.getSelectedItem();
long rowid = cursor.getLong(cursor.getColumnIndex("_id"));


Array Adapters

http://stackoverflow.com/questions/2390102/how-to-set-selected-item-of-spinner-by-value-not-by-position


You have to access the ArrayAdapter directly: Suppose your Spinner is named mySpinner, and it contains as one of its choices: "some value". To find the position of "some value" in the Spinner use this:
String myString = "some value"; //the value you want the position for
ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
//set the default according to value
mySpinner.setSelection(spinnerPosition);

1 comment: