views:

299

answers:

1
  • I have an xml layout file which contains a few widgets including a Spinner
  • I want to display a list of strings in the spinner, the list is generated at runtime as a result of a function so it can not be in arrays.xml.

I tried doing:

String[] SpinnerItems = GetMyCustomItems();

((Spinner)findViewById(R.id.MySpinner)).setAdapter(new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,SpinnerItems));

But this crashes my application.

What would be the correct way to accomplish this?

A: 

Have a look at this example http://d.android.com/resources/tutorials/views/hello-spinner.html

It looks like you are missing a couple of things when implementing your Spinner and adapter

Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
disretrospect
I do not want to use ArrayAdapter.createFromResource since the data (strings) that I want to show are not in an array resource but in a result from a function. That example does not apply to my situation.
Mervin
Ok, you don't need to use createFromResource to instantiate your ArrayAdapter but you should use android.R.layout.simple_spinner_item instead of android.R.layout.simple_list_item_1 and you need to setDropDownViewResource to be android.R.layout.simple_spinner_dropdown_item
disretrospect
i'm now using this constructor "public ArrayAdapter (Context context, int resource, int textViewResourceId, List<T> objects)" with android.R.layout.simple_spinner_item ,android.R.layout.simple_spinner_dropdown_item (also tried switching those 2 , still it makes my app crash.
Mervin
Can you post your error stack that is printed to logcat, otherwise I can only guess at what the problem is. Try using ArrayAdapter(Context context, int textViewResourceId, T[] objects) as I think you need to call the setDropDownViewResource rather the set the resource in the constructor.
disretrospect
The Console/LogCat tabs doesn't list any information regarding the error as far as I can see, and setDropDownViewResource is not available on Spinner classes it seems.
Mervin
No it is the adapter that has the setDropDownViewResource not the Spinner. The example posted on the Android Developer site is good. If you follow it as closely as you can, you should get there with it.
disretrospect
Somehow magically it's working now .. (I had to restart eclipse 2 times though) ArrayAdapter<String> ArrAdpt = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item,new String[] {"hey","working"}); ArrAdpt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); ((Spinner)findViewById(R.id.MapSelector)).setAdapter(ArrAdpt);thanks for the help
Mervin