Search code examples
androidlistviewandroid-cursoradapter

ListView with custom CursorAdapter doesn't work well


In a part of my android application I have a ListView that shows list of entries in a table. When user tap on a ListView item a new Intent for this item is shown.

In the new intent user can do some operations on this entry as reading, editing, favoriting (and unfavoriting when item is already favorited). In the detail intent I change the "marked" column of the entry in its table to 1 when it is favorited and to 0 when unfavorited.

It works fine. But the problem is in my master ListView. I set a custom CursorAdapter for my ListView. I wanted to add ImageView that indicates weather the entry is favorited or not. In the layout file of my ListView item I added an ImageView for this and set its visibility to GONE.

I want to detect favorited item and set its star ImageView visibility to VISIBLE. Then I ran the application in my device. As usual none of the entries is favorited. Then tapped on the first item in the ListView and details page for this item opened. I favorited it and went back to the list.

Ok, now there is a star icon on the fist item, but not only on this but also some other items. The detail page for these wrong starred items says that it is not favorited. So the problem is not with my database operations. Also I checked cursor that shows marked items and its .getCount() also said that only 1 item favorited. I can't find where there is the problem. I wrote my simplified source code for custom CursorAdapter bellow:

public class HereIsMyAdapter extends CursorAdapter {

    private final LayoutInflater mInflater;

    public HereIsMyAdapter(Context context, Cursor cursor) {
        super(context, cursor, true);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView txtTestText = (TextView) view.findViewById(R.id.txtTestText);
        ImageView imgMark = (ImageView) view.findViewById(R.id.imgMark);

        txtSureAz.setText(cursor.getString(cursor.getColumnIndex("azname")));

        boolean isMarked = cursor.getInt(cursor.getColumnIndex("marked")) == 1 ? true : false;

        if (isMarked) {
            imgMark.setVisibility(0);
        }

    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = mInflater.inflate(R.layout.my_list_item, parent, false);
        bindView(view, context, cursor);
        return view;
    }

}

Solution

  • have you tried with something like?

    boolean isMarked = cursor.getInt(cursor.getColumnIndex("marked")) == 1;
    if (isMarked) {
        imgMark.setVisibility(View.VISIBLE);
    }else{
        imgMark.setVisibility(View.GONE);
    }