I have a Spinner which is filled by a SimpleCursorAdapter within the onResume() method. The selection is also set in onResume: spinner.setSelection(x).
When I go to another activity and then go back to this activity, the Spinner shows the text of the first item, instead of the text of the selected item.
How do I fix this?
EDIT: Here’s my code:
@Override
public void onResume(){
super.onResume();
fillSpinner();
}
private void fillSpinner() {
Db = new DbAdapter(this);
Db.open();
final Cursor cursor = Db.getCats(true,true);
startManagingCursor(cursor);
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);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
cursor.moveToPosition(pos);
spinnerval = cursor.getInt(cursor.getColumnIndexOrThrow(DbAdapter._ID));
Log.d("spinnerval", spinnerval+"");
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.setSelection(0);
int now = hour*60*60+minute*60;
Log.d("fillSpinner","now="+now+" / "+now/60.0/60.0);
cursor.moveToFirst();
while(cursor.moveToNext()){
int s = cursor.getInt(cursor.getColumnIndexOrThrow(DbAdapter.KEY_START));
int e = cursor.getInt(cursor.getColumnIndexOrThrow(DbAdapter.KEY_END));
if(e<s){
if(now>s){
e+=24*60*60;
}
else{
s-=24*60*60;
}
}
if(s<=now&&e>now){
spinner.setSelection(cursor.getPosition());
}
}
Db.close();
spinner.invalidate();
}
EDIT2: Screenshot:

Changing
spinner.setSelection(cursor.getPosition())tospinner.setSelection(cursor.getPosition(),true)did the trick.