views:

586

answers:

3

Hi!

I have a Spinner View that's populated through a SimpleCursorAdapter. Based on the selection I need to save the rowid in the entry database (position won't work because things can be added and deleted from the Spinner Database). This I can do by using spinner.getAdapter().getItemId(pos) . But When I edit an entry I need to make the Spinner position selected that is associated with this rowid (currently).

spinner.setSelection(position) won't work because I have the rowid, I need a way to find the current position of the item in the current spinner based on the rowid in the database.

A: 

Had an idea when writing this, made a hashtable with rowid->pos when populating the spinner and then used that. Might help someone if they're searching.

awiden
+1  A: 

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"));

There might be a quicker way to do it, but that's always worked for me.

Erich Douglass
Thanks for your answer!
awiden
If it was helpful for you, consider marking it as the accepted answer by clicking the checkbox on the left of the question.
Erich Douglass
A: 

Why do it the hard way when you can do it the right way?

I refer to the manual:

http://d.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29

example code:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            int index = spinner.getSelectedItemPosition();
            Toast.makeText(getBaseContext(), 
                "You have selected item : " + index + " which is row " + id, 
                Toast.LENGTH_SHORT).show();                
        }
        public void onNothingSelected(AdapterView<?> arg0) {}
    });

Thanks to evancharlton on #android-dev for this enlightment. :)

moijk