[英]How to delete an item from both database as well as listview Android?
使用Arrayadapter在列表視圖上顯示存儲在數據庫中的元素。 現在,我想同時從列表視圖和數據庫中刪除項目。 請幫我解決。
要從數據庫中刪除行,請嘗試使用示例http://codinglookseasy.blogspot.in/2012/08/sqlite-database.html 。 從數據庫中刪除后,從arrayadapter中刪除該項目,並使用adapter.notifyDataSetChanged()從列表視圖中刪除它
考慮使用游標適配器將列表視圖綁定到數據庫表。 這里有一個例子: http : //thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/
該示例使用了不推薦使用的“ startManagingCursor”,為了支持CursorLoader,不推薦使用該參數。 一旦最終實現了CursorLoader,它就是很好的選擇。 您注冊了一些偵聽器,並且UI會立即更新以反映對數據庫的任何更改(而無需在列表視圖中手動添加/刪除行)。
這是我的代碼:
Cursor c = db.rawQuery("SELECT * FROM BOOKMARKS", null);
ID = c.getColumnIndex("ID");
audiotime=c.getColumnIndex("BookmarkTime");
// Check result.
c.moveToFirst();
if (c != null)
{
// Loop through all Results
do
{
/*String str=c.getString(ID);
audiobooks.add(str);*/
str=c.getString(audiotime);
audiobooks.add(str);
}
while(c.moveToNext());
c.close();
db.close();
//TODO
arrayAdapter=new ArrayAdapter<String>(this, R.layout.row3, R.id.itemr1,audiobooks);
lv.setAdapter(arrayAdapter);
cursor.close();
db.close(); //close db resources
}
public void onClick(View v)
{
if(v.getId()==R.id.Delete)
{
db = openOrCreateDatabase("DB", 0, null);
db.delete("BOOKMARKS", null, null);
int j=lv.getCount();
Toast.makeText(GetAudioBookmarks.this, " after delete listview count " +j,Toast.LENGTH_SHORT).show();
}
我無法做到這一點,因為我僅將書簽字符串添加到了列表視圖。 我粘貼了將從數據庫獲取數據並添加到listview的代碼。 現在,我的代碼將像單擊刪除按鈕一樣刪除數據庫上的所有項目,但listview的計數將保持不變,但不會在listview上顯示任何數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.