Android Spinner onNothingSelected

Jannik Marker Vangsgaard picture Jannik Marker Vangsgaard · Sep 30, 2014 · Viewed 7.4k times · Source

In my app i have a spinner with 3 values.

If you press the first one it should go to the Activity: UploadPicture

if you press the second one it should go to the Activity: ChangePassword

if you press the last one it should go to the Activity: Login

But since spinner has the first value at launch, there seems no way to trigger the onItemSelected if you pick the first one. (i do not want a forth value with : "please select one" ). So my question is how do i trigger the onNothingSelected? because when i pick the first value it does not trigger the onItemSelected.

My code:

@Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {
            System.out.println(pos + " " + first);
            if (!first && pos == 0) {

            goUpload();
            } else if (!first && pos == 1) {
                goInternReportActivity();
                //spinner.setSelection(0);

            } else if (!first && pos == 2) {
                goTeksterActivity();
                //spinner.setSelection(0);
            }
            first = false;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

            goUpload();
        }

Answer

Crawler picture Crawler · Sep 30, 2014

I once had same issue and wanted to use onNothingSelected callback.

I discovered that we cannot use onNothingSelected and onItemSelected together if item at index 0 also has some method like yours.

As per documentation Spinner onItemSelectedcallback is invoked only when:

  1. the newly selected position is different from the previously selected position

  2. if there was no selected item.

So, index 0 item is always selected even if you don't touch your spinner. Even it's not what you want to do: A fourth value "Select Action" in index 0 is best solution to solve your problem.