我正在使用listView,并且每一行都有一个按钮。我使用的是OnClick,而不是监听器。 当我按下按钮时,我需要更新数据库。我怎么知道ID是什么? 这是我的代码:
public void saleButtonClick(View v) {
int quantity = 0;
TextView mQuantityTextView = (TextView) findViewById(R.id.main_quantity);
quantity = Integer.parseInt(mQuantityTextView.getText().toString());
if (quantity > 0){
quantity --;
Uri updateUri = ContentUris.withAppendedId(BookEntry.CONTENT_URI, v.getId());
ContentValues values = new ContentValues();
values.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
int rowsUpdated = getContentResolver().update(
updateUri,
values,
null,
null);
if (rowsUpdated == 1) {
Toast.makeText(this, R.string.sellable, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.not_sellable, Toast.LENGTH_SHORT).show();
}
} else {
// Out of stock
Toast.makeText(this, R.string.out_of_stock, Toast.LENGTH_LONG).show();
}
mQuantityTextView.setText(Integer.toString(quantity));
}
答案 0 :(得分:0)
如果将ListView与CursorAdapter(+ ContentProvider)一起使用,则应在CursorAdapter中添加onClickListener。在这种情况下,所有列表项都将具有与产品关联的SaleButton(具有唯一ID)。 在您的适配器中尝试以下代码:
Button saleButton = view.findViewById(R.id.sale_button);
saleButton.setOnClickListener(v -> {
sellItem(_id, productQuantity);
});
/**
* helper method for sell a product
* @param id - id of product
* @param productQuantity - original quantity which must decreased by one
*/
private void sellItem(long id, int productQuantity) {
int newQuantity = --productQuantity;
// check that new quantity is greater than 0. In this case we update product
if (newQuantity > 0) {
ContentValues sellItem = new ContentValues();
sellItem.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
int result= mContext.getContentResolver().update(ContentUris.withAppendedId(BookEntry.CONTENT_URI,id),sellItem,null,null);
if(result==1){
// rest of your code
}
}
}
希望有帮助。 我有一个非常类似的项目,请看一下:https://github.com/csongi77/InventoryApp 最好的祝福!