我需要帮助检索我的ListView项ID,以添加删除功能。 我的ListView填充了以下代码:
ListView BookList = (ListView)findViewById(R.id.listView1);
DbAdapter db = new DbAdapter(getApplicationContext());
db.open();
Cursor cursor = db.fetchAllBooks();
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.book, cursor, new String[]{DbAdapter.KEY_TITLE,DbAdapter.KEY_AUTHOR},new int[]{R.id.booktitle,R.id.bookauthor});
BookList.setAdapter(adapter);
if(cursor.moveToFirst()) {
while (cursor.moveToNext());
}
db.close();
我的删除代码在DbAdapter类中设置为:
//delete a book
public boolean deleteBook(long bookID) {
return database.delete(DATABASE_TABLE, KEY_BOOKID + "=" + bookID, null) > 0;
}
任何帮助?
完整资料来源:pastebin.com/kKgePkPM
答案 0 :(得分:0)
如果我理解正确,您可以将onitemclicklistener添加到listview,然后使用行id将其从数据库中删除,如果bookid与行ID相同。
BookList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (db.deleteBook(position)) { // Success!
// remove from listview data source here
adapter.notifyDataSetChanged();
}
}
});
答案 1 :(得分:0)
您必须为listView添加一个侦听器。最好的方法是设置
bookList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// DO YOUR STUFF HERE
}
});
在那里,您将获得视图和点击的位置。通过视图或位置,您可以获得“deletebook”方法所需的值。
答案 2 :(得分:0)
尝试在getView
方法中添加类似内容:
Button btnDelete = (Button) convertedRowView.findViewById(R.id.btnDeleteCustom);
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int itemPos = 4; // This is position of item in ArrayList
deleteBook(getItemId(itemPos));
}
});