Search code examples
androidspinnersimplecursoradapter

How to position (select) a spinner on specific item by id with simplecursoradapter?


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.


Solution

  • 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;
            }
        }
    }