Reputation: 89
I use custom CursorAdapter and ViewHolder pattern, i want to know how to keep data for each row.
For example, keeping favorites value (true or false)
My ViewHolder:
private static class ViewHolder {
int column_id, column_gtext, column_isfav, column_isread;
TextView tvText;
ImageView btnFavorites;
boolean changeDefaultFav; // if btnFav clicked its change
}
My newView:
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//return null;
View view = LayoutInflater.from(context).inflate(R.layout.goftar_lr_default, parent, false);
ViewHolder holder = new ViewHolder();
holder.tvText = (TextView)view.findViewById(R.id.goftar_text);
holder.btnFavorites = (ImageView)view.findViewById(R.id.bg_fav);
holder.tvText.setTypeface(font);
holder.column_id = cursor.getColumnIndexOrThrow("_id");
holder.column_gtext = cursor.getColumnIndexOrThrow("gtext");
holder.column_isfav = cursor.getColumnIndexOrThrow("isfav");
holder.column_isread = cursor.getColumnIndexOrThrow("isread");
holder.changeDefaultFav = false;
holder.tvGoftarText.setText(holder.tvGoftarText.getText() + "\n" + "Append NewView");
view.setTag(holder);
return view;
}
My bindView:
@Override
public void bindView(final View view, Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder)view.getTag();
holder.tvText.setText(cursor.getString(holder.column_gtext));
final int position = cursor.getPosition();
holder.btnFavorites.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int newValue = 1;
if(holder.changeDefaultFav == true) {
holder.changeDefaultFav = false;
newValue = 0;
}
cursor.moveToPosition(position);
dh.openDatabase();
dh.updateFavorites(cursor.getInt(holder.column_id), newValue);
dh.close();
}
});
Please help me, thanks so much :)
Upvotes: 0
Views: 75
Reputation: 30985
The purpose of the ViewHolder
is to give you quick access to the subviews inside the view so you only call findViewById()
when you create the view.
You are assigning model values (from the cursor) into your ViewHolder
in newView()
. That will cause problems because when your view is recycled, newView()
will not be called, only bindView()
. So you must read your cursor data within bindView()
.
You ask, How to keep data for each row in custom CursorAdapter? The data is already stored within the cursor, so all you have to do is move that data from the cursor into the views. ViewHolder
just helps you set up the view so access to things like TextView
, etc is very fast [compared to findViewById()
]
You should remove all your column fields from ViewHolder
and assign cursor data values to TextView
s etc. in bindView()
.
Look at some more tutorials to try to understand more about how view recycling works in ListView
.
Upvotes: 1