I'm currently attempting to override a simplecursor adapter to allow me to use a imagbutton for each listitem.
Code so far:
public class MyCursorAdapter extends SimpleCursorAdapter {
Cursor mCursor;
final int tIndex;
final class ViewHolder{
public TextView textView;
public ImageButton imageButton;
}
public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
mCursor = c;
tIndex = mCursor.getColumnIndex(DBAdapter.TASK);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)){
ViewHolder viewHolder;
final int i = position;
if (convertView == null){
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.listview,parent,false);
viewHolder.textView = (TextView)convertView.findViewById(R.id.taskName);
viewHolder.imageButton = (ImageButton)convertView.findViewById(R.id.edit_task);
viewHolder.imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("LOG_TAG", "It Works: " + i);
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
String task = mCursor.getString(tIndex);
viewHolder.textView.setText(task);
}
return convertView;
}
}
I use my parent activity to display the contents of the database, and use an alternate activity to add data to the database. I call finish() on the alternate activity to ensure the user is returned to the parent activity, in the parent activity in the onResume() method I use:
@Override
protected void onResume() {
super.onResume();
cursor.moveToFirst();
myCursorAdapter.swapCursor(cursor = db.getAllRows());
list.startLayoutAnimation();
amountTasks();
}
When the user is returned to the parent activity, the data is incorrectly showed, the text of the listview will be a duplicate of the last entry, and the position will be 0.
I have found that if i change the return statement to:
return super.getView(position,convertView,parent)
The text is correctly shown, but the position still returns 0.
Any idea why this is happening?
Solution was to use bindview instead of getview, also much simpler to implement.
Credit to Stewart & pskink:
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
final int i = cursor.getPosition();
ViewHolder viewHolder = new ViewHolder();
viewHolder.imageButton = (ImageButton)view.findViewById(R.id.edit_task);
viewHolder.imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("LOG_TAG","Position: "+i);
}
});
}
getview override wasn't necessary.