1

I'm populating a spinner with a number of records from my SQlite database using the following code:

    DBHelper db = new DBHelper(getBaseContext());
    Cursor cursor_clients = db.select("clients", "_id, name", "ORDER BY name"); // table, fields, filter/order

    String[] columns = new String[] { "name" };
    int[] to = new int[] { android.R.id.text1 };

    SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_clients, columns, to, 0);
    mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
    spnClients.setAdapter(mAdapter);

It works great, and I can use

spnAcademias.getSelectedItemId();

To get the _id of the selected record. My problem is: How to select an item on this spinner by the _id?

I have the _id of the row I want, I want it to show this row selected, and not the first row coming from the query.

Victor Hugo
  • 109
  • 1
  • 12

2 Answers2

2

Doing more research I ended up with the solution here: setSelection on Spinner based on rowId

I thought maybe there was a native solution without a loop, but there is not.

Solution:

public void setSpinnerItemById(Spinner spinner, int _id)
{
    int spinnerCount = spinner.getCount();
    for (int i = 0; i < spinnerCount; i++)
    {
        Cursor value = (Cursor) spinner.getItemAtPosition(i);
        long id = value.getLong(value.getColumnIndex("_id"));
        if (id == _id)
        {
            spinner.setSelection(i);
            break;
        }
    }
}
Athena
  • 302
  • 4
  • 16
Victor Hugo
  • 109
  • 1
  • 12
0

If you're able to just as easily get the text value of the row you are looking for, then try the solution here, and more specifically the top comment on it: Set selected item of spinner programmatically

Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).

...

... I also found a way of getting the index without needing to loop through the adapter. I used the following mySpinner.setSelection(arrayAdapter.getPosition("Category 2"));

Community
  • 1
  • 1
naweinberger
  • 429
  • 5
  • 10