Android Spinner add items
Question
I'm working on an App and need some help with the spinner widget.
The array has no entries by its creation and will be filled in another function. So I have to use adapter.add(item);
and spinner.setAdapter(adapter);
to update the spinner in this function, I guess.
// global variables String[] test = new String[100]; int x = 0; Spinner s; ArrayAdapter adapter; Button btn1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn1 = (Button) findViewById(R.id.button1); btn1.setOnClickListener(this); s = (Spinner) findViewById(R.id.spinner1); adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, test); } public void onClick(View arg0) { test[x] = String.valueOf(x);; x++; adapter.add(test[x]); s.setAdapter(adapter); }
just for education purpose I tried this, but there is still a bug in the onClick() function. Something has to be done with the ArrayAdapter, I guess. But I don't familiar with this and didn't found an example for adding itmes by pressing a button. Maybe there is just a simple failure somewhere else, but currently I just don't see it.
here the complete code:
ArrayList<Integer> test; int x = 0; Spinner s; ArrayAdapter adapter; Button btn1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn1 = (Button) findViewById(R.id.button1); btn1.setOnClickListener(this); s = (Spinner) findViewById(R.id.spinner1); test = new ArrayList<Integer>(); adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, test); } public void onClick(View arg0) { test.add(x); x++; s.setAdapter(adapter); }
Solution
You are adding x to an array element then passing this element to the adapter.add method. This is effectively the same as using: adapter.add(x);.
Why not use an ArrayList instead of a array. ArrayLists are dynamic, and do not need to be given an initial size. A very quick check has shown me that there is a constructor for an Array Adapter that is compatible with ArrayLists and I expect any descendant of the List class. See the code example below.
ArrayList<Integer> test = new ArrayList<Integer>();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, test);
I know this is not a complete solution to your problem, but just a pointer to a possibly better way of doing it.
Do a web search with the terms ‘android updating arrayAdapter at runtime’ and I am sure you will stumble upon a more concrete example.
OTHER TIPS
The problem is you are setting the ArrayAdapter
's data to be a 100 null strings, and then adding to the end of that when you press the button. Try changing your test
variable to be new String[0]
.
Then in your onClick
method, just call adapter.add(String)
. It will add it to the end of your current data, so you don't need to give it a big enough array initially.