我一直在寻找没有运气,这是我的代码
// Product List
public void setProductList() {
productDB = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.list);
listAdapter = listView.getAdapter();
Cursor prodView = productDB.getAllData();
prodView.moveToFirst();
ArrayAdapter<String> listAdaptor = new ArrayAdapter<String>(this, R.layout.medicinelistmenu, R.id.productlistsTextView1);
while (prodView.moveToNext()) {
listAdaptor.add(prodView.getString(1));
}
listView.setAdapter(listAdaptor);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
productDB.deleteProduct(id);
Toast.makeText(medicineList.this, "Item Deleted", Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
return true;
}
});
}
使用 onItemLongClick 函数,其他帖子告诉我 AdapterView 中的 long 值将是 SQLLite ID 列,但它与数组中的位置值相同。
这是我的 DatabaseHelper 类中的删除函数
public void deleteProduct(long ID)
{
SQLiteDatabase productsdb = this.getWritableDatabase();
productsdb.execSQL("DELETE FROM "+ PRODTABLE_NAME +" WHERE ID = "+ ID);
}
任何人都可以阐明如何获取数据库 ID 值吗?
最佳答案
Long 是被单击项目的行 ID,而不是数据库中产品的 ID。
在 DBHelper 类中创建一个返回 ID
的方法,参数为 String ProductName
编辑onItemLongClick()
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
TextView prdName = arg1.findViewById(R.id.textView_prdname);
// now call the method which take productName as parameter and return productId
int prdID = productDB.getProductID(prdName.getText().toString());
// Now Pass that ID to deleteProduct
productDB.deleteProduct(prdID);
Toast.makeText(medicineList.this, "Item Deleted", Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
return true;
}
此外,如果名称是唯一的而不是DELETE FROM table WHERE ID = id
,您可以使用
DELETE FROM table WHERE NAME = name
这里的name可以通过prdName.getText()
获取
这样你只需要执行一个查询即可。
关于java - SQLite ID 列和 onItemLongClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314667/