Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set spinner selection by id not position

Tags:

android

I have created a simple Spinner binding it to a SimpleCursorAdapter. I'm populating the SimpleCursorAdapter with a list of towns from a content provider.

When I go to save the users selection I'm planning on saving the row id that is being populated into my SimpleCursorAdapter.

I'm using the following code to get the ID.

townSpinner.getSelectedItemId();

What I can not figure out is how best to set the selection when I pull back up the saved item.

The following code works but it only sets selection by position number.

townSpinner.setSelection(2);

Should I just create a loop to determine the correct position value based on Id?

long cityId = Long.parseLong(cursor.getString(CityQuery.CITY_ID));

for (int i = 0; i < citySpinner.getCount(); i++) {              
    long itemIdAtPosition2 = citySpinner.getItemIdAtPosition(i);
    if (itemIdAtPosition2 == cityId) {
        citySpinner.setSelection(i);
        break;
    }
}
like image 589
zachariahyoung Avatar asked Dec 11 '10 22:12

zachariahyoung


1 Answers

I think you've answered your own question there! Just write your own setSelectionByItemId method using the code you posted

like image 85
FrinkTheBrave Avatar answered Sep 19 '22 00:09

FrinkTheBrave