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.

2 Answers 2

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; } } } 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I've seem that solution, but I want to select the item via _id and not the name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.