I’m trying to populate a spinner with a SimpleCursorAdapter. But the spinner is totally empty; it just doesn’t show items. I do not get error messages.
I’ve been trying to figure out what I am doing wrong for hours. I really hope you can help me.
This is the onCreate function in my activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.insert);
spinner = (Spinner) findViewById(R.id.spinner);
fillSpinner();
}
This is the function that should populate the spinner:
private void fillSpinner() {
Db = new DbAdapter(this);
Db.open();
final Cursor cursor = Db.getCats(true,true);
Log.d("fillSpinner","cursor.getCount: "+cursor.getCount()+" / cursor.getColumnCount: "+cursor.getColumnCount());//returns 8 and 4
String[] from = new String[]{DbAdapter.KEY_NAME};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, from, to);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//...
cursor.close();
Db.close();
}
And this is my getCats() function in my DbAdapter class:
public Cursor getCats(boolean times, boolean adapter) {
String id = KEY_ID;
if(adapter){
id = KEY_ID +" "+_ID;
}
String columns = id+", "+KEY_NAME;
if(times){
columns+=", "+KEY_START+", "+KEY_END;
}
return Db.rawQuery("SELECT "+columns+" FROM "+CATS_TABLE+" ORDER BY "+KEY_ID+" ASC", null);
}
And my constants:
private static final String CATS_TABLE = "cats";
public static final String KEY_ID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_START = "start";
public static final String KEY_END = "end";
public static final String _ID = "_id";
Thanks in advance!
Yellos
Don’t close the cursor.
The cursor must remain open while you use the spinner. After you call the cursor let the system handle closing it by calling
startManagingCursor. It will close it when you are done w/o you having to worry about it.