Android: ListView with complex data model

I would like to display an array of "complex" data in a ListView. In a very simplified form, my data model will look something like this:

class ListPlacesValues { String idObject; String name; String city; String country; ArrayList<String> classification; double distance_quantity; DistanceUnit distance_unit; [...more stuff ...] } 

I know that I can convert my complex data to a HashList and then just use the SimpleAdapter:

  SimpleAdapter mAdapter = new SimpleAdapter( this, hashList, R.layout.places_listitem, new String[] { "name", "city", "country"}, new int[] { R.id.name, R.id.city, R.id.country} ); 

However, I would prefer to use my data model directly, but I don’t know where and how to start, so in the end I can do something like this:

 ArrayList<ListPlacesValues> values = getData(); MyAdapter mAdapter = new MyAdapter( this, values, R.layout.places_listitem, ListPlacesValues { values.name, values.city, values.country}, new int[] { R.id.name, R.id.city, R.id.country} ); 

Solution: I found this Android API example ( List14 ), which was really useful.

+4
source share
2 answers

You can extend the ArrayAdapter. Here is a sample code for you. In this example, SearchItem is a custom POJO. Basically, you need to override the getView () method to build your row by inflating the layout of the row and then populating the values ​​based on the list of elements and current position

 class SearchItemsAdapter extends ArrayAdapter<SearchItem> { Activity context; List<SearchItem> items; SearchHeader header; @SuppressWarnings("unchecked") public SearchItemsAdapter(final Activity context, final Map<SearchHeader, List<SearchItem>> result) { super(context, R.layout.item, (List) ((Object[]) result.values() .toArray())[0]); this.context = context; this.header = result.keySet().iterator().next(); this.items = result.get(this.header); } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { final View view = this.context.getLayoutInflater().inflate( R.layout.item, null); final SearchItem item = this.items.get(position); ((TextView) view.findViewById(R.id.jt)).setText(item.jt); ((TextView) view.findViewById(R.id.dp)).setText(item.dp); ((TextView) view.findViewById(R.id.cn)).setText(item.cn); ((TextView) view.findViewById(R.id.loc)).setText(item.loc.name); final TextView body = ((TextView) view.findViewById(R.id.e)); body.setText(item.e); body.setTag(item.src[0]); ((TextView) view.findViewById(R.id.src)).setText(item.src[1]); return view; } } 
+4
source

In the sample you linked to

There is one error with conversion.
 if(convertView != null){ //reuse convertView.setAnimation(null); convertView.setAnyCustomFieldsIdontWantFilledWithData(null); } 

you want to set all animations or unused fields to null, otherwise your objects may have data in them or the animations that await you do not want to.

+1
source

All Articles