Skip to content Skip to sidebar Skip to footer

Cursoradapter Bindview Optimization

When overriding ArrayAdapter I know is correct using a pattern like this: if(view != null){ ...create new view setting fields from data }else return view; //reuse view is co

Solution 1:

In CursorAdapter, you get layout in newView and bind data in bindView. CursorAdapter already do reuse pattern in getView so you don't have to do it again. Below is the original getView source code.

public View getView(int position, View convertView, ViewGroup parent) {
    if (!mDataValid) {
        thrownew IllegalStateException("this should only be called when the cursor is valid");
    }
    if (!mCursor.moveToPosition(position)) {
        thrownew IllegalStateException("couldn't move cursor to position " + position);
    }
    View v;
    if (convertView == null) {
        v = newView(mContext, mCursor, parent);
    } else {
        v = convertView;
    }
    bindView(v, mContext, mCursor);
    return v;
}

If you want further optimization using ViewHolder Pattern here is example: Create tag in newView and retrieve in bindView

publicclassTimeListAdapterextendsCursorAdapter {
     private LayoutInflater inflater;
     privatestaticclassViewHolder  {
         int    nameIndex;
         int    timeIndex;
         TextView   name;
         TextView   time;
    }
  publicTimeListAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
  this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }
  @OverridepublicvoidbindView(View view, Context context, Cursor cursor) {
         ViewHolderholder=   (ViewHolder)    view.getTag();
         holder.name.setText(cursor.getString(holder.nameIndex));
         holder.time.setText(cursor.getString(holder.timeIndex));
  }
  @Overridepublic View newView(Context context, Cursor cursor, ViewGroup  
  p parent) {
         Viewview=   inflater.inflate(R.layout.time_row, null);
         ViewHolderholder=newViewHolder();
         holder.name    =   (TextView)  view.findViewById(R.id.task_name);
         holder.time    =   (TextView)  view.findViewById(R.id.task_time);
     holder.nameIndex   =   cursor.getColumnIndexOrThrow 
         (TaskProvider.Task.NAME);
         holder.timeIndex   =   cursor.getColumnIndexOrThrow    
         (TaskProvider.Task.DATE);
         view.setTag(holder);
    return view;
  }
}

Solution 2:

Yes, getView is in Adapter and is not dependant from ArrayAdapter nor CursorAdapter.

recycling is always a good practice. Ensure that your code sets a colour in every situation.

Post a Comment for "Cursoradapter Bindview Optimization"