2011-10-16 27 views
0

有很多關於如何從列表中刪除項目的問題,但我無法找到我正在尋找的項目。
所以基本上,我有一個列表和數據庫,如何從列表和數據庫中刪除?
因爲我的列表從ArrayList<String>填充,所以一個項目只是字符串。例如,我在我的列表中有兩個項目,如 - 1.John,Doe 2.Jane,Doe
如何獲得這些項目ID?
如果我用這個代碼,並通過點擊項目檢查ID:如何在Android中從列表和數據庫中刪除項目?

listView.setOnItemClickListener(new OnItemClickListener() { 
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

Toast.makeText(getApplicationContext(), 
    Long.toString(parent.getItemIdAtPosition(position)) , 
    Toast.LENGTH_SHORT).show(); }}); 

它顯示0或1,但沒有1或2(這是相當合乎邏輯)
所以啊,我怎麼讓這些項目IDS?我現在唯一可以考慮的是獲取我的列表項的前兩個或三個字符,並將它們轉換爲int並傳遞給我的SQL語句,然後從數據庫中刪除相應的項目。
也許有人有更好的想法?

編輯:

private void getAllData() 
{ 
    cursor = myDataBase.rawQuery("SELECT * FROM " + 
      MY_TABLE, null); 

    if (cursor != null) 
    { 
     if (cursor.moveToFirst()) 
     { 
      do 
      { 
       int id = cursor.getInt(cursor.getColumnIndex("Id")); 
       String persName = cursor.getString(cursor.getColumnIndex("Name")); 
       String persSurname= cursor.getString(cursor.getColumnIndex("Surname")); 
       results.add("" + id + ", " + persName + ", " + persSurname); 
      } while (cursor.moveToNext()); 
     } 
     cursor.close(); 
    } 
} 

而且resultsprivate List<String> results = new ArrayList<String>();我希望這是你在問什麼。

+0

我可以看到如何你從數據庫中檢索數據,然後如何你得到'String'對象的一些代碼你想進入適配器? – Pzanno

+0

@Pzanno在我的文章中添加了代碼。 – randomUser56789

+0

是啊,這幾乎是我在找的東西。我發佈了一個應該適合你的答案,並且還建議使用'SimpleCursorAdapter'將來可能從數據庫創建的列表。 – Pzanno

回答

1

你或許應該從SimpleCursorAdapter類擴展的,而不是你目前正在做,只在String對象傳遞什麼。這example,應該讓你開始把你的數據放入適配器。

但是,如果您只想修改您目前正在做的事情,我會提出以下建議。除了你的ArrayList<String> results,我還會創建一個額外的對象ArrayList<Integer> resultsIds,它可以保存每個項目的ID。

results.add("" + id + ", " + persName + ", " + persSurname); 
resultsIds.add(id); 

然後在點擊監聽做到以下幾點:

@Override 
protected void onListItemClick(ListView listView, View view, int position, long id) { 
    super.onListItemClick(listView, view, position, id); 
    int id = resultsIds.get(position); // this is the id for the item in the database you want to delete 
    // now with your myDataBase SqliteDatabse object delete the item from the databse. 
    // then remove it from the list 
    ArrayAdapter adapter = (ArrayAdapter) getListAdapter(); 
    adapter.remove(results.get(position)); 
    // and you'll probably now want to remove the String and id from your results 
    results.remove(position); 
    resultsIds.remove(position); 
} 
+0

非常感謝,你解決了我的問題。 – randomUser56789

0

使用onListItemClick和參數ID而不是:

@Override 
protected void onListItemClick(ListView listView, View view, int position, long id) { 
    super.onListItemClick(listView, view, position, id); 

    //TODO: 
} 
相關問題