1

The user enters a number in an EditText, the app then programmatically creates that many spinners. I am having problems getting the positions of those spinners to save them when the user clicks the "save" button at the bottom of my UI.

When I try to get the position with: mArraySpinner.add(spinner.getSelectedItemPosition()); as seen below I have several empty locations in the array like the listener is firing on creation and then it will only save the last spinners position in the last element of the array.

Here is the code that I create the spinners with:

for(int i = 1; i <= numStockTanks; i++) {
        TableRow tR = new TableRow(this);
        // creates the textView
        tV1 = new TextView(this);
        tV1.setText("Stock Tank #" + i + " size: ");

        // add spinner to row
        spinner = new Spinner(this);
        ArrayAdapter<CharSequence> adapterStockTankSize = ArrayAdapter.createFromResource(
                this, R.array.StockTankSize, android.R.layout.simple_spinner_item);
        adapterStockTankSize.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapterStockTankSize);
        spinner.setTag(i + 600);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onNothingSelected(AdapterView<?> parent) {}
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                mArraySpinner.add(spinner.getSelectedItemPosition());
            }
        });

        // add the TextView and the editText to the new TableRow
        tR.addView(tV1);
        tR.addView(spinner);

        // add the TableRow to the TableLayout
        tL.addView(tR,new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));    
    } // end for statement

thanks for your help

GingerHead
  • 8,130
  • 15
  • 59
  • 93
deerkiller11
  • 165
  • 1
  • 12

1 Answers1

0

You are reassigning the spinner variable each time, but the onItemSelected method is using this variable. You need to redeclare this spinner variable each time so that the method is looking for a unique Spinner object.

Change spinner = new Spinner(this); to final Spinner spinner = new Spinner(this);, and remove whatever declaration of spinner you have already.

Cat
  • 66,919
  • 24
  • 133
  • 141
  • this is working with one exception, it still appears to be firing on create. any thoughts? – deerkiller11 Jul 31 '12 at 00:01
  • Yes, this is the expected behavior. `onItemSelected` will be called whenever the `Spinner` is changed; this includes when it is first set. Your best bet is to monitor this (with a `private boolean`) and only fire your code after the initial set. – Cat Jul 31 '12 at 00:17