I have an Android application with a Spinner
and want to fill it dynamically with my own objects. The objects do exist already as a List<T>
.
The objects are of type Category
:
public class Category implements Serializable {
private Long id;
private String name;
// constructors
// getter & setter
// hashCode, equals
// toString
}
I know that I have to write a Adapter. How do I do that? I've tried to find some examples... no luck. Please advice.
I am not sure if this helps, but the Android SDK has a nice little example of supplying data to a Spinner from an array. Converting a List to an array is trivial, so maybe this will point you in the right direction.
http://developer.android.com/resources/samples/Spinner/src/com/android/example/spinner/SpinnerActivity.html
Good luck.
This is a simple example. Don't be fooled by the "cursor" name, it's just using a List. The idea is simple: extend from
BaseAdapter
and implement any missing methods (it's an abstract class); and don't forget to override thegetView()
method to provide the "visual" representation of yourCategory
.Here is my 5 cents. I had a similar problem. I was working with SimpleCursorAdapter which implements interface SpinnerAdapter, but arrived only until SDK version 11 (Android 3.0). I intended my app to work with SDK 8 (Android 2.2) and up, so I had to replace SimpleCursorAdapter with another, or my own. The real challenger was that I also used a custom XML layout for spinner and in it showed several fields from cursor i.e. cursor adapter. So here is my solution after a lot of research, and the info wasn't easy to come by.
Here is the layout file used in spinner named spin_layout.xml :
And here is the adapter implementing SpinnerAdapter and extending (using as a little helper) BaseAdapter. The Cursor that was used originally was transformed into List and passed in constructor, together with activity containing the spinner.
Unlike other solutions you find on the web, method getItemId establishes link with id field from database, just like SimpleCursorAdapter. That id is the argument passed in onItemSelected(AdapterView arg0, View arg1, int position, long id) in OnItemSelectedListener for spinner.setOnItemSelectedListener. Method getView inflated spin_layout.xml, identifies the two views contained in layout and assigns them values (as String!).