22

I have been using values of spinner from XML string-arrays so far like:

Spinner karant_sp; 
karant_sp = (Spinner) findViewById(R.id.spinner1); 
ArrayAdapter<CharSequence> karant_adapter = ArrayAdapter.createFromResource(this, R.array.karant_list, android.R.layout.simple_spinner_item);
karant_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
karant_sp.setAdapter(karant_adapter);
karant_sp.setSelection(0);
karant_sp.setOnItemSelectedListener(new select_karant());

Can I use a local java ArrayList-String as the list of items to be displayed in drop down menu?

Something like:

Spinner karant_sp; 
ArrayList<String> return_likes = new ArrayList<String>();
return_likes.add("Hello");
return_likes.add("world");
karant_sp = (Spinner) findViewById(R.id.spinner1); 
ArrayAdapter<CharSequence> karant_adapter = ArrayAdapter.createFromResource(this, return_likes, android.R.layout.simple_spinner_item);
karant_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
karant_sp.setAdapter(karant_adapter);
karant_sp.setSelection(0);
karant_sp.setOnItemSelectedListener(new select_karant());

I know the above code doesn't work, but I would like to know something which works using ArrayList-string.

1
  • And why you are using 2 arraylist.... your arr is refering to Global arraylist but not the arraylist in which you are saving your data Commented Feb 12, 2015 at 10:22

1 Answer 1

54

Yes. Just don't call createFromResource() on your Adapter. Use one of the constructors instead. Something like

ArrayAdapter<String> karant_adapter = new ArrayAdapter<String>(this,
     android.R.layout.simple_spinner_item, return_likes);

This is just an example you might have to change something else to get it working depending on what isn't working. But The ArrayAdapter Docs should help.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the most simplest way which can be used to populate spinner dynamically[+1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.