删除listview上的项目和数据库[ANDROID]

时间:2013-03-08 12:54:29

标签: android database sqlite listview

我已经检查了与我自己有关的所有问题。我正在使用恕我直言的代码完全不同。到目前为止,我已将所有内容编码。我已经读过,删除数据库中的数据只是通过传递位置,问题是数据库中自动生成的id与传递的位置不一样。我想要实现的是在删除列表视图中的项目后,数据库中的项目也将被删除。

获取所有数据的数据库代码:

public ArrayList<String> getData() {
    String[] columns = new String[] { KEY_ID, KEY_CLIENT_NAME,
            KEY_PRODUCT_NAME, KEY_SUPPLIER_PRICE, KEY_BS_PRICE, KEY_QTY,
            KEY_TOTAL_AMOUNT };
    Cursor c = sql.query(DB_TABLE, columns, null, null, null, null, null);

    ArrayList<String> result = new ArrayList<String>();

    int id = c.getColumnIndex(KEY_ID);
    int cName = c.getColumnIndex(KEY_CLIENT_NAME);
    int pName = c.getColumnIndex(KEY_PRODUCT_NAME);
    int suppPrice = c.getColumnIndex(KEY_SUPPLIER_PRICE);
    int bsPrice = c.getColumnIndex(KEY_BS_PRICE);
    int qty = c.getColumnIndex(KEY_QTY);
    int totalAmount = c.getColumnIndex(KEY_TOTAL_AMOUNT);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        result.add("ID: " + c.getInt(id) + "\n" + "CLIENT NAME: "
                + c.getString(cName) + "\n" + "PRODUCT NAME: "
                + c.getString(pName) + "\n" + "SUPPLIER PRICE: "
                + c.getString(suppPrice) + "\n" + "RETAIL PRICE: "
                + c.getString(bsPrice) + "\n" + "QUANTITIY: "
                + c.getString(qty) + "\n" + "TOTAL: "
                + c.getString(totalAmount) + "\n");
    }

    return result;
}

检索数据的代码:

sql = new SQLDatabase(this);
    sql.open();
     ArrayList<String> data = sql.getData();
    sql.close();

应该执行删除的代码:

protected void onListItemClick(View view, int position, long id) {
    Log.i("TAG", "onListItemClick id=" + position + id);


      AlertDialog.Builder builder = new AlertDialog.Builder( Delete.this);

      builder.setMessage("WHAT DO YOU WANT TO DO?");
      builder.setNegativeButton("DELETE", new
      DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) { }
                   // DELETE CODE HERE
      });

      builder.setNeutralButton("CANCEL", new
      DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) { }
                // DO NOTHING
      });

      builder.setCancelable(false); AlertDialog alertdialog =
      builder.create(); alertdialog.show();

}

1 个答案:

答案 0 :(得分:0)

在您插入的列中添加标记,并在列表和数据库中删除操作时使用相同的标记值。