Jean-Philippe Roy Jean-Philippe Roy - 1 year ago 121
Android Question

Spinner.setSelection doesn't trigger OnItemSelectedListener properly

I'm currently working on a Account Management Activity for my Android application and I'm having trouble figuring out why the setSelection() method from a spinner does not trigger the OnItemSelectedListener attached to said Spinner.

Here is what I have currently;

onCreate() method :

public void onCreate(Bundle savedInstanceState) {



// Vérification si l'usager est déjà connecté
Globals appState = ((Globals) this.getApplication());
boolean userLoggedIn = appState.isUserLoggedIn();
boolean userInfoAvailable = appState.isUserInfoAvailable();

if (userLoggedIn && userInfoAvailable) {

Pertinent lines from the initializeUI() method which is called on the Activity's creation which shows the binding of the Spinner the Listener :

/** OnItemSelectedHandler for the Country Spinner */
mCountrySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "onCountrySelected() was called, position : " + pos);

mProvinces = new ArrayList<String>();
mProvincesCode = new ArrayList<String>();


for (int i = 0; i < mXML.getCountry(pos).sizeProvinces(); i++){

mProvinceArrayAdapter = new ArrayAdapter<String>(ManageAccountActivity.this,
android.R.layout.simple_spinner_item, mProvinces);

public void onNothingSelected(AdapterView<?> arg0) {
// Do Nothing ...

And again another couple lines, this time from the fillUI method() :

Log.i(TAG, "Setting country based on user information.");
((Spinner) findViewById(
// TODO : Fix Provinces and States not being changed accordingly
Log.i(TAG, "Setting province based on user information.");
((Spinner) findViewById(

So with this I would expect the OnItemSelectedListener to be called right after I set the selection in the fillUI() method, but that's not what's happening at runtime :S

Here's my LogCat extract that shows that the Listener isn't called when the selection is applied to the country spinner:

I/ManageAccountActivity(28108): Setting country based on user information.

I/ManageAccountActivity(28108): Setting province based on user information.

I/ManageAccountActivity(28108): onCountrySelected() was called, position : 1

As an experiment, I also tried putting the fillUI() call in the onStart method of my Activity but that didn't change how the application reacted.

Thanks in advance for any pointers, help or tips !

Answer Source

Have you tried to set the spinner by using two arguments, the second using a boolean:

.setSelection(mProvincesCode.indexOf(mUser.getProvince()), true); 

From the developers page it shows:

setSelection(int position, boolean animate)
//Jump directly to a specific item in the adapter data.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download