当listview中的复选框在Android中更改时更新数据库

时间:2015-04-21 16:47:15

标签: android listview checkbox

我通过字段在数据库中存储复选框。该字段返回01(表示falsetrue)。这是自定义适配器中的代码:

public class CauHoiAdapter extends ArrayAdapter<CauHoiObject> {
    Context mContext;
    ArrayList<CauHoiObject> arlCauHoi = new ArrayList<CauHoiObject>();
    String cauHoi = null;

    CauHoiDAO cauhoidao = new CauHoiDAO(getContext());

    public CauHoiAdapter(Context context, int resource,
            ArrayList<CauHoiObject> objects) {
        super(context, resource, objects);
        // TODO Auto-generated constructor stub
        this.mContext = context;
        this.arlCauHoi = new ArrayList<CauHoiObject>(objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.item_cauhoi, parent, false);

        ImageView imgCauHoi = (ImageView) rowView
                .findViewById(R.id.img_cauhoi_icon);
        TextView txtCauHoi = (TextView) rowView.findViewById(R.id.textCauHoi);
        CheckBox chkFavorate = (CheckBox) rowView
                .findViewById(R.id.star_favorite);
        cauHoi = arlCauHoi.get(position).getCauHoi();
        imgCauHoi.setImageResource(arlCauHoi.get(position).getIconCauHoi());
        txtCauHoi.setText(arlCauHoi.get(position).getCauHoi());
        chkFavorate.setChecked(arlCauHoi.get(position).isFavorate());

        chkFavorate.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked){
                    cauhoidao.updateYeuThich(cauHoi, 1);
                }
                else{
                    cauhoidao.updateYeuThich(cauHoi, 0);
                } 

            }
        });
        return rowView;
    }

如何在复选框点击时更改数据库?

1 个答案:

答案 0 :(得分:0)

在适配器中进行此类更改绝不是一个好主意,为此,我建议您制作一个监听器并在活动中使用它,因此适配器只需在mainActivity中执行某些操作,您也可以使用viewholder模式来提高性能,将在这里留下一个有用的教程,很好地解释适配器,以便您可以解决这个问题

Tutorial Vogella Listviews

希望我能帮忙,祝你好运