Fill spinner from cursor in android
i have searched for a awnser for this for a while today. It all looks so easy but i never get it to work. I want to fill a spinner with my cursor. I have be开发者_JAVA技巧en trying to use SimpleCursorAdapter for this as a lot of sites say i shall but i never get it to work. Show me just how easy it is :)
Thanks for your time!
My cursor
Cursor cursor = db.query(DATABASE_TABLE_Clients, new String[] {"_id", "C_Name"}, null, null, null, null, "C_Name");
My spinner
(Spinner) findViewById(R.id.spnClients);
My Code
Cursor cursor_Names = SQLData.getClientNames();
startManagingCursor(cursor_Names);
String[] columns = new String[] { "C_Name" };
int[] to = new int[] { R.id.txt_Address };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_dropdown_item, cursor_Names, columns, to);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
The following code solved my problem. I was missing .setDropDownViewResource. After that i used simple_spinner_dropdown_item so i don't have to make my own layout.
Cursor cursor_Names = SQLData.getClientNames();
startManagingCursor(cursor_Names);
String[] columns = new String[] { "C_Name" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_Names, columns, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
I don't see a View for your dropdown in your code. Something like:
mAdapter.setDropDownViewResource(R.layout.spinner_view_dropdown);
Of course you need to have a spinner_view_dropdown.xml file in your res/layout directory.
I have done it
empresasSpinner = (Spinner) findViewById(R.id.empresasSpinner);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, empresasAll.toArray(new EntidadObject[0]));
empresasSpinner.setAdapter(spinnerArrayAdapter);
A simple DTO
public class EntidadObject {
private int id;
private String nombre;
//GETTES and SETTERS
}
The part DAO
public class EntidadDao {
//...
public List<EntidadObject> getEmpresas() {
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM empresas", null);
List<EntidadObject> entidadObjects = new ArrayList<EntidadObject>();
cursor.moveToFirst();
do {
EntidadObject entidadObject = new EntidadObject();
entidadObject.setId(cursor.getInt(0));
entidadObject.setNombre(cursor.getString(1));
entidadObjects.add(entidadObject);
} while (cursor.moveToNext());
return entidadObjects;
}
}
So then I can catch the ID of the select item with
EntidadObject eo = (EntidadObject)empresasSpinner.getSelectedItem();
eo.getId();
精彩评论