Spinner OnclickListener event executes twice -
where as implementation of listener is as :
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Problem definition
I want to save user selected text into data storage, when user choose any item from spinner, and I am able to do this. But my another task is that to show previously selected item (access from data storage) as selected item in spinner, but each time when I call spinner's activity, spinner shows first item as default selected item, and also in data storage it make change previous item to default.
How can I make difference between 'Spinner initialization' and 'User selected manually' events?
You have to handle both events logically. As these references (Android Spinner selection, problem on spinner) says that you have to use flag variable to handle this, I am putting a code sample.
Hope this will help you to clear your logic.
public class TestActivity extends Activity {
//Checks report spinner selection is default or user selected item
private boolean isDefaultSelection;
//Spinner setup
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// Set true at onCreate
isDefaultSelection = true;
spinner = (Spinner) findViewById(R.id.id_of_spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String> (this, R.layout.drop_down_custom_row, data);
//Implement custom view for drop down of spinner
//spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(isDefaultSelection) { //If spinner initializes
spinner.setSelection("Set_here_id_of_data_item_from_storage_which_was_previously_stored");
isDefaultSelection = false;
} else { //If user manually select item
int itemPosition = spinner.getSelectedItemPosition();
//Write here code to store selection (itemPosition) of user into data storage
}
}
public void onNothingSelected(AdapterView<?> parent) {
//User selected same item. Nothing to do.
}
});
}
}
Hope it will clear your doubt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With