i have a spinner load data to sqlite
i have field id and field name in database.
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin2.setAdapter(dataAdapter);
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
and the result is
USA -> value is "USA"
France -> value is "France"
when i change the code labels.add(cursor.getString(1));
to labels.add(cursor.getString(0));
and the result is
1 -> value is "1"
2 -> value is "2"
i try with int position2 = spin2.getSelectedItemPosition()+1;
but the value is id/position of spinner , not the id of database.
how to display field name on spinner. but the value is id of name
Example: The spinner display:
USA -> value is "1"
France -> value is "2"
BR
Alex
It is really simple, what you can do is to implement/ represent what you need by a class, in the following manner :
Create the following class : SpinnerObject
Using this class, you can still use the Android implementation of the ArrayAdapter (no need to implement your own, since the toString method provides the string value that you want to display, and you still store the database id that you also need).
Now you will have to create your list as follows :
Now that you have the list of objects with the values and ids, you load the spinner this way :
And the spinner will display the values, while having their ids (from the database) too.
In order to retrieve the id of the currently selected item, you do this :
Please try it and let me know what happens.