Spinner.setSelection doesn't trigger OnItemSelectedListener properly
Asked Answered
M

3

18

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 :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.account_management);

    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    retreiveLanguage();
    initializeUI();

    // 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) {
      fillUI();
    }
}   

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>();

            mXML.parseResponse(FileManager.getInstance().getPortalOptions());

            for (int i = 0; i < mXML.getCountry(pos).sizeProvinces(); i++){
                mProvinces.add(mXML.getCountry(pos).getProvince(i).getLabel(mLanguage));
                mProvincesCode.add(mXML.getCountry(pos).getProvince(i).getCode());
            }

            mProvinceArrayAdapter = new ArrayAdapter<String>(ManageAccountActivity.this, 
                    android.R.layout.simple_spinner_item, mProvinces);
            mProvinceArrayAdapter.setDropDownViewResource(
                    android.R.layout.simple_spinner_dropdown_item);
            mProvinceSpinner.setAdapter(mProvinceArrayAdapter);
        }

        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(R.id.spin_country))
    .setSelection(mCountriesCode.indexOf(mUser.getCountry()));
// TODO : Fix Provinces and States not being changed accordingly
Log.i(TAG, "Setting province based on user information.");
((Spinner) findViewById(R.id.spin_province))
    .setSelection(mProvincesCode.indexOf(mUser.getProvince())); 

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 !

Madelina answered 30/1, 2012 at 14:43 Comment(2)
,OnItemSelectedListener is fired only when you do some action on spinner..to changeSolferino
Well I do change it ... moving the selection from 0 to 1 wouldn't that be considered changed ?Madelina
I
27

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.
Inhalant answered 30/1, 2012 at 15:46 Comment(6)
I've tried it with the animate argument being false (got it from another thread) I'll try it with the argument being set to true.Madelina
Well thank you very much, I should've tried setting it to true in the first place :P. Setting both spinners' to setSelection(pos, true) did the trick.Madelina
I've just tested this and using the method with animate indeed triggers onItemSelected while the one without does not.Erotic
Why is Android so broken!Magnetoelectricity
does not work for me either :( @AmanGoel answer also does not work for meAzarria
I've lost 2hours looking for this answer. How it can be so hard do this simple thing?Grassy
V
5

Just use the following code:

  ownerSpinnerVw.post(new Runnable() {
        @Override
        public void run() {
             ownerSpinnerVw.setSelection(position);
        }
    });
Vehicular answered 10/2, 2016 at 12:8 Comment(0)
M
0

I found the solution to my problem being adding this to the onCreate method. The program works but only for the first selection. The second time I select the program crashes the emulator.

spinner.setOnItemSelectedListener(this);

enter image description here

Montfort answered 1/11, 2016 at 16:59 Comment(1)
As you mentioned in your post. This answer is not working. Please add it as a comment.Fridlund

© 2022 - 2024 — McMap. All rights reserved.