1 回答

TA貢獻1871條經驗 獲得超8個贊
理想情況下,您將在視圖中可檢索的地方使用主鍵(或者反之亦然,使用已在可檢索的地方使用的值作為主鍵)。由于這里的主鍵是一個auto_increment
字段,因此它與您嘗試刪除的視圖之間沒有真正可靠的關聯(至少從我在您的代碼中看到的)。一種方法是Adapter
為您的列表使用自定義項,而不是ArrayAdapter
, 并使用View.setTag()
和View.getTag()
方法來存儲列表中每個項目的主鍵。
假設您的activity_listitem
布局有一個TextView
with id?text_view
,您在其中顯示從數據庫獲取的文本,并且您已添加存儲主鍵的標簽,您可以在主活動中執行以下操作:
? ? listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
? ? ? ? @Override
? ? ? ? public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
? ? ? ? ? ? TextView textView = (TextView) view.findViewById(R.id.text_view);
? ? ? ? ? ? final Integer which_item = (Integer) textView.getTag();? ? //Assuming you stored the ID as an Integer
? ? ? ? ? ? int rowsDeleted = bookmarksDB.deleteSpecificContent(which_item);
? ? ? ? ? ? if(rowsDeleted == 0){? //should be 1, since we're deleting by Primary Key
? ? ? ? ? ? ? ? //if you would like like, handle if nothing was deleted
? ? ? ? ? ? }
? ? ? ? ? ? return true;
? ? ? ? }
? ? });
在您的 BookmarksDatabase 類中:
? ? public int deleteSpecificContents(int id) {
? ? ? ? SQLiteDatabase db = this.getWritableDatabase();
? ? ? ? return db.delete(TABLE_NAME, COL1 + "=?", new String[]{Integer.toString(id)});
? ? }
如果您不想使用自定義Adapter,另一種方法是使用列表中的位置來確定要刪除的項目。您可以通過查詢數據庫并迭代Cursor直到它與列表中項目的位置匹配來完成此操作。
? ? listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
? ? ? ? @Override
? ? ? ? public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
? ? ? ? ? ? Cursor data = bookmarkDB.getListContents();
? ? ? ? ? ? int i = 0;
? ? ? ? ? ? while(data.moveToNext()){
? ? ? ? ? ? ? ? if(i == position){
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? i++;
? ? ? ? ? ? }
? ? ? ? ? ? int rowsDeleted = bookmarkDB.deleteSpecificContent(data.getInt(0));
? ? ? ? ? ? //again, handle if rowsDeleted != 1 if you want
? ? ? ? ? ? return true;
? ? ? ? }
? ? });
您的BookmarkDatabase.deleteSpecificContent()方法與第一種方法完全相同 - 唯一的區別在于如何確定要刪除的項目的 id。如果您不想處理deleteSpecificContent()不返回 1 的情況(除非我在這里遺漏了一些主要內容,否則在您的用例中它應該始終返回 1),請隨意將其簽名更改為void, 而不是int。
請注意,第二種方法比第一種方法更昂貴,因為它需要額外的數據庫查詢,并且可能會迭代很多Cursor。雖然它需要更少的新/更改的代碼,但可能不建議使用(老實說我不能肯定地說。這可能適合您的用例,具體取決于您的數據庫的大小,但是 - 完全披露 - 我是沒有足夠的 Android 經驗來撥打此電話。請自行決定使用)。
添加回答
舉報