15

I have created a spinner which is automatically updated with appliance names when a person adds an appliance using an array adapter. I created an OnItemSelected method with the spinner so when one of the names in the spinner is selected, a new window appears. However the OnItemSelected is automatically selecting the first item on the list when the activity starts and so the user does not have a chance to actually make a selection until the new window appears.

Here is the code:

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {
    // TODO Auto-generated method stub
    startActivity(new Intent("com.lukeorpin.theappliancekeeper.APPLIANCESELECTED"));
    }

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

Does anyone know a way in which the first item on the list wont be automatically selected?

Here is the code for the rest of the spinner:

ArrayAdapter<String> appliancenameadapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, ApplianceNames); //Sets up an array adapter containing the values of the ApplianceNames string array
    applianceName = (Spinner) findViewById(R.id.spinner_name); //Gives the spinner in the xml layout a variable name
    applianceName.setAdapter(appliancenameadapter); //Adds the contents of the array adapter into the spinner

    applianceName.setOnItemSelectedListener(this);
Sketzii
  • 181
  • 1
  • 2
  • 10
  • Are you calling setSelection on the Spinner? What's the rest of your Activity code look like? – twaddington Apr 12 '12 at 22:57
  • I've added the code into the main question, thanks – Sketzii Apr 12 '12 at 23:27
  • possible duplicate of [How to keep onItemSelected from firing off on a newly instantiated Spinner?](http://stackoverflow.com/questions/2562248/how-to-keep-onitemselected-from-firing-off-on-a-newly-instantiated-spinner) – David d C e Freitas Jan 28 '15 at 12:46

5 Answers5

24

If you are trying to avoid the initial call to your listener's onItemSelected() method, another option is to use post() to take advantage of the view's message queue. The first time the spinner checks for your listener it won't be set yet.

// Set initial selection
spinner.setSelection(position);

// Post to avoid initial invocation
spinner.post(new Runnable() {
  @Override public void run() {
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // Only called when the user changes the selection
      }

      @Override
      public void onNothingSelected(AdapterView<?> parent) {
      }
    });
  }
});
James Wald
  • 13,626
  • 5
  • 52
  • 63
9

Does anyone know a way in which the first item on the list wont be automatically selected?

There is always a selection on Spinner, and you cannot change that.

IMHO, you should not be using a Spinner to trigger starting an activity.

That being said, you can use a boolean to track whether this is the first selection event, and ignore it if it is.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • How would I go about creating a boolean flag for this? I'm very new to java, thanks – Sketzii Apr 12 '12 at 23:58
  • Add a `boolean isFirstSelection=true;` data member to your activity. In `onItemSelected()`, if `isFirstSelection==true`, then just flip it to `false`, otherwise call `startActivity()`. Newcomers to Java should spend some time learning Java outside of Android before doing any Android development. – CommonsWare Apr 13 '12 at 00:02
  • Thank you for helping, I've managed to solve it using a boolean flag – Sketzii Apr 13 '12 at 00:52
  • @CommonsWare Do you know how to manage this case with `Spinners` used in the rows of a `ListView`? The method `getView()` can be called multiple times for each row, so I guess we can not use the boolean approach in this case... Any ideas? I implemented this using buttons and AlertDialogs with SingleChoice items filled from a Cursor; but this is actually a "hack". – Caumons Apr 15 '12 at 22:06
  • 3
    @Caumons: I would never dream of putting `Spinners` in a `ListView`. – CommonsWare Apr 15 '12 at 22:13
  • @CommonsWare I needed this as I am listing "participations" of students to school and for each one the user can select a comment. I did it with buttons and AlertDialogs, as I was not able to manage Spinners in that scenario. – Caumons Apr 15 '12 at 22:19
8

It worked for me,

private boolean isSpinnerInitial = true;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view,
            int position, long id) {

        if(isSpinnerInitial)
        {
            isSpinnerInitial = false;
        }
        else  {
            // do your work...
        }

    }
karan
  • 3,319
  • 1
  • 35
  • 44
  • with this first position is not selected – Deepak Jun 19 '15 at 12:02
  • can't you read question... It simply says "How to make On Item Selected not automatically choose the first entry" So its for all developers who don't want 1st position selected. – karan Jun 19 '15 at 12:36
  • Ya I understand the answer. I have same requirement but onItemSelected , Item on the position first is not selected, I had to select the 2nd position item and then first position get selected. Hope u now understand what im saying – Deepak Jun 22 '15 at 04:08
0

Declare variable isSpinnerInitial then make Make a Selection as your default selection

spinnertaggeview.setSelection(-1); does not make selection as -1 or everything unselected as we do in .Net or other language . So you can ignore thatline.

testStringArrayListinside.add("Make a Selection");
ADD this line so that this is selected by default and user never selects it 

testStringArrayList = (ArrayList<String>) ClinqLinX.get("Tag");
                boolean added = false;
             testStringArrayListinside.add("Make a Selection");
                for (String s : testStringArrayList) {
                    if (s != null || s != "") {
                        String[] results = s.split(","); // split on commas

                        for (String string : results) {

                            testStringArrayListinside.add(string);
                            Toast.makeText(getContext(), string, Toast.LENGTH_SHORT).show();
                            added = true;
                        }
                    }

                }
                if (added == false) {
                    testStringArrayListinside.add("Not tagged details found");
                }

                spinnertaggeview.refreshDrawableState();

            }

            // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
            // and the array that contains the data
            if (testStringArrayListinside.size() > 0) {
                adapter = new ArrayAdapter<String>(this.getContext(),android.R.layout.select_dialog_singlechoice, testStringArrayListinside);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                // Here, you set the data in your ListView
                spinnertaggeview.setAdapter(adapter);
                 isSpinnerInitial = true;

                spinnertaggeview.setSelection(-1);
                spinnertaggeview.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                                               int arg2, long arg3) {
                        if (isSpinnerInitial){

                            isSpinnerInitial = false;

                            return;}
                        else{
                        TextView tv = (TextView) arg1;
                        String spinner_value = tv.getText().toString();
                        if (spinner_value.length() == 0) {
                            spinner_value = "Nothing";
                        }
                        String strusername = spinner_value;//As you are using Default String Adapter
                        Toast.makeText(getContext(), strusername, Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(spinnertaggeview.getContext(), Userdetails.class);
                        intent.putExtra("Username", strusername);
                        spinnertaggeview.getContext().startActivity(intent);}

                    }
Jin Thakur
  • 2,711
  • 18
  • 15
0

fast copi-paste:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    boolean isInit=false;
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (!isInit){isInit=true; return;}
            //CODE HERE!
        }
    @Override
    public void onNothingSelected(AdapterView<?> parentView) {}
});
Barrrettt
  • 645
  • 7
  • 15