我的以下代码显示了listview中sqlite的数据。现在我想写长按以删除listview和sqlite中的行。请帮我。我怎么能这样做?
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
R.layout.cartformat,results));
getListView().setTextFilterEnabled(true); }
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " + title + ", Quantity: " + qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}}}
答案 0 :(得分:1)
最好的方法是开发自定义适配器。但如果你不想要,这应该有效:
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList(){
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
String currentString = results.get(position);
String resultRegexString = "Title\\: ([^,]+), Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(resultRegexString);
if(resultRegexMatcher){
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3));
database.delete("CART", whereClause, null);
}
}
results.remove(position);
displayResultList();
});
}