I have spinner control and data items bind from sqlite using ormlite, this way:
public void addItemsOnSpinner()
{
DatabaseManager.init(this);
spinner = (Spinner) findViewById(R.id.spinner2);
List list = new ArrayList();
List<Countries> cList = DatabaseManager.getInstance().getAllCountry();
for (Countries c : cList)
{
list.add(c.getcName());
}
ArrayAdapter dataAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
So basically, countries names are set as items for my spinner control. It works, however I'm not satisfied with this, because I can only determine current selection by label selected in spinner. Obviously, it's not good because country name is not guaranted to be unique (it's just simple app for education puroposes).
The best solution is to store in my spinner both country name (as spinner label visible for user) and corresponding record id. Id is autogenerated value and of course it's unique, so it can be used to determine selection and read all other propertis from database, using id value, or edit seleted record and save new info to database.
I know how to read/edit record by id. But I have no idea how to store corresponding records ids in my spinner to get know which item was actually selected and how to query database.
Any ideas?
My spinner control is declared as:
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/select2" />
I added storing ids as tags, so:
List list = new ArrayList();
List ids = new ArrayList();
List<Countries> cList = DatabaseManager.getInstance().getAllCountry();
for (Countries c : cList)
{
list.add(c.getcName());
ids.add(c.getcID());
}
ArrayAdapter dataAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setTag(ids);
Is this ok? Also - how to get current selection tag? For get current item I used: String.valueOf(spinner.getSelectedItem())
but how to read current tag to get my id?