nico
nico

Reputation: 1067

Android: create/update Spinner from ArrayList, how?

On the start of the program,the Spinner is created by

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    spinnerAdapter = ArrayAdapter.createFromResource(
            this, R.array.IDs, android.R.layout.simple_spinner_item);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerAdapter);

    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

at a later Point, all entrys should be replaced by Items out of an ArrayList. When using the Spinner, only the String is interesting to me. On showing and later in the algorithm.

How would you do that?

for (String object:out){
    System.out.println("added to spinner: "+object);
    spinnerAdapter.add(object);
    }


    spinnerAdapter.notifyDataSetChanged();

That was my idea, but it seems much too simple as it only throws exceptions.

Edit:

As asked, here the exception thrown..

12-11 15:11:38.538: I/System.out(280): added to spinner: TheSwitch 12-11 15:11:38.548: W/dalvikvm(280): threadid=7: thread exiting with uncaught exception (group=0x4001d800) 12-11 15:11:38.568: E/AndroidRuntime(280): FATAL EXCEPTION: Thread-8 12-11 15:11:38.568: E/AndroidRuntime(280): java.lang.UnsupportedOperationException 12-11 15:11:38.568: E/AndroidRuntime(280):    at java.util.AbstractList.add(AbstractList.java:411) 12-11 15:11:38.568: E/AndroidRuntime(280):     at java.util.AbstractList.add(AbstractList.java:432) 12-11 15:11:38.568: E/AndroidRuntime(280):     at android.widget.ArrayAdapter.add(ArrayAdapter.java:178) 12-11 15:11:38.568: E/AndroidRuntime(280):    at de.enocean.EnOceanAppActivity.updateSpinner(EnOceanAppActivity.java:109) 12-11 15:11:38.568: E/AndroidRuntime(280):  at de.enocean.EnOceanAppActivity$1.useNotifyMessage(EnOceanAppActivity.java:222) 12-11 15:11:38.568: E/AndroidRuntime(280):     at de.enocean.EnOceanAppActivity$1.run(EnOceanAppActivity.java:179) 12-11 15:11:38.568: E/AndroidRuntime(280):  at java.lang.Thread.run(Thread.java:1096)

Upvotes: 1

Views: 6222

Answers (1)

Alexander
Alexander

Reputation: 48262

It looks like adapters created from resources are immutable. You could, probably, populate your adapter in code like this

String[] myStrings = {"One", "Two", "Three" };
ArrayAdapter<String> adapter = new ArrayAdapter(YourActivity.this, android.R.simple_spinner_adapter, myStrings);
spinner.setAdapter(adapter);

I think the adapter created this way will allow adding/deleting of values

Upvotes: 3

Related Questions