You can use the getSelectedItem
method to get the value of a selected item.
Create the following class SpinnerObject :
public class SpinnerObject {
private int databaseId;
private String databaseValue;
public SpinnerObject ( int databaseId , String databaseValue ) {
this.databaseId = databaseId;
this.databaseValue = databaseValue;
}
public int getId () {
return databaseId;
}
public String getValue () {
return databaseValue;
}
@Override
public String toString () {
return databaseValue;
}
}
Now you will have to create the list as follows:
public List < SpinnerObject> getAllLabels(){
List < SpinnerObject > labels = new ArrayList < SpinnerObject > ();
// Seleciona todas as consultas
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Loop através de todas as linhas e adicionando à lista
if ( cursor.moveToFirst () ) {
do {
labels.add ( new SpinnerObject ( cursor.getString(0) , cursor.getString(1) ) );
} while (cursor.moveToNext());
}
// Fecha conexão
cursor.close();
db.close();
return labels;
}
Now that you have the list of objects with values and ids, you load Spinner as follows:
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
List <SpinnerObject> lables = db.getAllLabels();
// Criando adaptador para o spinner
ArrayAdapter<SpinnerObject> dataAdapter = new ArrayAdapter<SpinnerObject>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Anexando adaptador de dados para o spinner
spn.setAdapter(dataAdapter);
}
spinner will display the values, even though they have their ids (from the database) as well.
To retrieve the ID of the selected item:
int itemId = Integer.parseInt(((SpinnerObject) spn.getSelectedItem()).getId());
Reference