Android應用開發—listview長按刪除該Item資料並刪除所在資料庫的記錄

來源:互聯網
上載者:User

1、先看下listview適配器

mlistItemAdapter = new SimpleAdapter(getApplicationContext(),mlistItem,// 資料來源R.layout.listviewitem, new String[] { "mtext", "mtime" },new int[] { R.id.ItemText, R.id.ItemTime });

2、index索引

int index = 0;// 長按刪除指定資料的索引

3、長按得到index

// 添加長按點擊,得到點中的index,即參數arg2mlistview.setOnItemLongClickListener(new OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {// TODO Auto-generated method stubindex = arg2;return false;}});

4、找到匹配的一項,並進行刪除

String deleteText = mlistItem.get(index).get("mtext").toString();String deleteTime = mlistItem.get(index).get("mtime").toString();SQLiteDatabase db = dbHelper.getReadableDatabase();// 以下是把所有的表都存進來,然後_id按順序排列,方便讀取資料Cursor cursor = db.query("user", null, null, null, null, null, null);while (cursor.moveToNext()) {String mtext = cursor.getString(cursor.getColumnIndex("mtext"));//得到資料庫中的資料String mtime = cursor.getString(cursor.getColumnIndex("mtime"));currentTime = new Date();// 通過主索引值來判斷點中的listview中的Item所對應的資料庫表中的_idif (deleteText.equals(mtext) && deleteTime.equals(Cursortime)) {deleteData(cursor.getInt(0));//刪除匹配的資料庫裡記錄,cursor.getInt(0)為得到該cursor對用的第一例,及_idbreak;}db.close();

5、deleteData(int )

public void deleteData(int index) {SQLiteDatabase db = dbHelper.getReadableDatabase();// 刪除表的所有資料// db.delete("users",null,null);// 從表中刪除指定的一條資料db.execSQL("DELETE FROM " + "user" + " WHERE _id="+ Integer.toString(index));db.close();}

附加:使用Thread進行資料更新,如不先清除原有的資料,就會在listview後面添加上相同的資料,所以在Handle中調用

// 清除原來的資料並更新mlistItemAdaptermlistItem.clear();mlistItemAdapter.notifyDataSetChanged();

之後再重新讀取資料庫,然後添加進mlistItem即可實現。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.