Tuesday, October 12, 2010

Android's ListView performance for large list

I needed to use a large ListView however the performance of the ListView loading time was very poor. Since I've used SimpleAdapter to map the data to the layout I was forced to populate all the data when creating the SimpleAdapter.

The solution I've decided to take is creating an adapter specific for the task, which populate the data from the objects only during creation of the item's view.

This is the pseudo code (note that the object data retrieval should by lazy too):

public class MyObjectAdapter extends BaseAdapter {
private ArrayList mData;
private int mResource;
private LayoutInflater mInflater;

public TimeZoneDisplayAdapter(Context context, ArrayList data,
int resource) {
mData = data;
mResource = resource;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
return mData.size();
}

@Override
public Object getItem(int position) {
return mData.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null)
v = mInflater.inflate(mResource, parent, false);
else
v = convertView;

bindView(position, v);
return v;
}

private void bindView(int position, View view) {
MyObject o = mData.get(position);

((TextView)view.findViewById(R.id.list_item_resource_id)).setText(o.getData1());
......
......
......
}
}

Note: there are few examples online how to load data to ListView using threads. This wasn't my problem, and it's like killing a fly with a sledge-hammer. The loading time of a specific item was very short, the problem was that there were simply too many items to load at construction time.

No comments: