列表视图项目不会通过自定义适配器从SQLite数据库中删除

时间:2014-03-12 12:19:41

标签: android sqlite listview custom-adapter

拥有一个自定义适配器,从数据库获取数据并通过列表视图显示。

我目前的代码将删除'行和刷新适配器以显示它已被删除但在重新加载页面时它会从数据库中提取数据库,因为它没有删除它。

请指教!!

适配器类:

    public class FoodListAdapter extends BaseAdapter {

    Context context;
    ArrayList<FoodListItems> foodList;
    DatabaseCommands sqlHandler;
    SQLiteDatabase db;
    ItemDatabase dbHelper;
    private final String COLUMN_NAME_ENTRY_ID = "entryid";
    private final String TABLE_NAME = "foodItems";
    private final String DATABASE_NAME = "ItemDatabase.sqlite";
    private final int DATABASE_VERSION = 12;
    long id;

    public FoodListAdapter(Context context, ArrayList<FoodListItems> list) {

        this.context = context;
        foodList = list;
    }

    @Override
    public int getCount() {

        return foodList.size();
    }

    @Override
    public Object getItem(int position) {

        return foodList.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

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

        FoodListItems FoodListItems = foodList.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_view_custom, null);

        }

        final ImageButton deleteButton = (ImageButton) convertView
                .findViewById(R.id.deleteItem);
        deleteButton.setTag(position);
        deleteButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                foodList.remove(position);
                System.out.println(position);
                dbHelper = new ItemDatabase(context, DATABASE_NAME, null,
                        DATABASE_VERSION);
                db = dbHelper.getWritableDatabase();
                db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + " ="
                        + deleteButton.getTag(position), null);
                db.close();
                notifyDataSetChanged();
            }
        });

        TextView itemTitle = (TextView) convertView.findViewById(R.id.itemName);
        itemTitle.setText(FoodListItems.getTitle());
        TextView itemQuantity = (TextView) convertView
                .findViewById(R.id.itemQuantity);
        itemQuantity.setText(String.valueOf(FoodListItems.getQuantity()));

        return convertView;
    }
}

我想我需要获取listview行的相应数据库ID,但我不知道如何。

所有帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用此:

db.delete(TABLE_NAME,COLUMN_NAME_ENTRY_ID + " = " + (position+1), null);

并且您没有指定和id值,因此请在删除按钮标记上设置唯一ID,或者您可以将位置设置为标记。