Create a class to represent a class :
public class Turma {
private String nome;
private int id;
public Turma(int id, String nome){
this.id = id;
this.nome = nome;
}
public int getId(){
return id;
}
public String getNome(){
return nome;
}
@Override
public String toString()
{
return nome;
}
}
The method that gets the classes of the bank should return a ArrayList<Turma>
:
public ArrayList<Turma> getTurmas(){
ArrayList<Turma> turmas = new ArrayList<Turma>();
Cursor cursor = db.query("turma", null, null, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
do{
int id = cursor.getInt(0);
String nome = cursor.getString(1);
Turma turma = new Turma(id, nome);
turmas.add(turma);
}while(cursor.moveToNext());
}
return turmas;
}
Where db
is an instance of SQLiteDatabase obtained through the getReadableDatabase()
method of its inherited class from SQLiteOpenHelper
Use this ArrayList to construct the adapter :
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, turmasArray);
The adapter will use the
toString()
method of the Class class to get the string that will appear in Spinner .
You can get the selected class in Spinner this way:
Turma turmaSelecionada = ((Turma)spinner.getSelectedItem());