Basically i have a method createList()
which creates a Spinner and then i add those spinners to an arrayList myList
. After adding them i use setOnItemSelectedListener
on each Spinner in the array List to get the position but no matter what i select in a spinner i get the position 0. Interestingly, if i don't add spinners to ArrayList and use only one spinner i get the position easily. The problem arises when i put spinner objects in an arrayList.
Here is the code:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
Spinner spinner1;
int pos;
ArrayList<Spinner> myList = new ArrayList<>();
int length = 0;
int[] numbers;
int show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.root);
}
public void showPosition(View view) {
numbers = new int[length];
for (int i = 0; i < length; i++) {
myList.get(i).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
numbers[i] = adapterView.getSelectedItemPosition();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
public void createList(View view) {
length++;
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this, R.array.city, android.R.layout.simple_spinner_item);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1 = new Spinner(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(500, 50);
spinner1.setLayoutParams(params);
spinner1.setAdapter(arrayAdapter);
myList.add(spinner1);
linearLayout.addView(spinner1);
}
}
When i print number
in the log all the elements of this array are zero no matter what item i have selected in the spinner.
Please help stuck on it for few days :(
Found the answer:
Directly get the position by mySpinner.get(i).getSelectedItemPosition()
and use that position with a switch statement to make it workable.