如何获取按钮单击列表视图项并保存到sqlite

时间:2015-02-01 18:20:58

标签: android sqlite listview listviewitem

我在listview中有四个textview和一个按钮。当用户点击按钮时,我想获得这四个文本视图的值并传递给数据库。我混淆了如何将所选项目的数据保存到sqlite。

public class PlannningListViewAdapter extends BaseAdapter{

    Context context;
    public ArrayList<Planning> planArraylist;
    private static LayoutInflater inflater = null;
    public Activity planActivity;

    public PlannningListViewAdapter(Context context,
            ArrayList<Planning> planArraylist) {
        this.context = context;
        this.planArraylist = planArraylist;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        return planArraylist.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.single_lv_item, null);
        }

        Planning p = planArraylist.get(position);

        TextView tvDocCode = (TextView) convertView.findViewById(R.id.Plan_no);
        TextView tvDocName = (TextView) convertView.findViewById(R.id.doc_name);
        TextView tvmon = (TextView) convertView.findViewById(R.id.mon);
        TextView tvAdr = (TextView) convertView.findViewById(R.id.adr);
        Button   btn_save =(Button)convertView.findViewById(R.id.button1);
        btn_save.setOnClickListener(ButtonClickListener);


        tvDocCode.setText(p.getDocCode());
        tvDocName.setText(p.getDocName());
        tvmon.setText(p.getTerrCode());
        tvAdr.setText(p.getAdr());
        return convertView;
    }
    private OnClickListener ButtonClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
           // Log.v(TAG, "item clicked, row %d", position);
        }
    };

}

1 个答案:

答案 0 :(得分:2)

您可以在按钮上使用setTag()getTag()方法。

请查看以下代码:

您必须更改getItem方法:

@Override
public Planning getItem(int arg0) {
    return planArraylist.get(arg0);
}

更新你的getView方法:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ...

    Button   btn_save =(Button)convertView.findViewById(R.id.button1);
    btn_save.setTag(position);

    ...
}


private OnClickListener ButtonClickListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        final int position = (int)v.getTag();
        Planning planning = getItem(position);
        yourDatabaseHelper. getRuntimeExceptionDao(Planning.class).createOrUpdate(planning);
    }
};

还有一件事。您应该实施ViewHolder请阅读有关此模式的信息,最适合您的解决方案是使用RecyclerView,已经在RecyclerView.ViewHolder中实现了获取位置。