How to make On Item Selected not automatically choose the first entry
Asked Answered
E

5

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);
Encode answered 12/4, 2012 at 22:48 Comment(3)
Are you calling setSelection on the Spinner? What's the rest of your Activity code look like?Lillie
I've added the code into the main question, thanksEncode
possible duplicate of How to keep onItemSelected from firing off on a newly instantiated Spinner?Heelpiece
W
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.

Wootten answered 12/4, 2012 at 23:7 Comment(6)
How would I go about creating a boolean flag for this? I'm very new to java, thanksEncode
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.Wootten
Thank you for helping, I've managed to solve it using a boolean flagEncode
@Wootten 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".Crustaceous
@Caumons: I would never dream of putting Spinners in a ListView.Wootten
@Wootten 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.Crustaceous
B
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) {
      }
    });
  }
});
Beckmann answered 19/2, 2013 at 17:7 Comment(0)
W
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.

Wootten answered 12/4, 2012 at 23:7 Comment(6)
How would I go about creating a boolean flag for this? I'm very new to java, thanksEncode
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.Wootten
Thank you for helping, I've managed to solve it using a boolean flagEncode
@Wootten 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".Crustaceous
@Caumons: I would never dream of putting Spinners in a ListView.Wootten
@Wootten 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.Crustaceous
S
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...
        }

    }
Sagacious answered 21/1, 2015 at 8:37 Comment(3)
with this first position is not selectedProhibit
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.Sagacious
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 sayingProhibit
F
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);}

                    }
France answered 24/8, 2015 at 21:51 Comment(0)
A
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) {}
});
Ailyn answered 8/3, 2022 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.