2013-10-12 31 views
0

我有一個SQLite數據庫是這樣的:的Android SQLite的decremente ID

private static final String CREATE_BDD = 
     "CREATE TABLE " + TABLE_NOTE + " (" 
     + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
     + COL_TITLE + " TEXT NOT NULL, " 
     + COL_NOTE + " TEXT NOT NULL, " 
     + COL_COLOR + " TEXT NOT NULL);"; 

數據庫存儲注意到,我可以通過ID來識別。當我從數據庫中刪除一個筆記時,我希望所有的ID高於所刪除的筆記的ID減1,那麼我可以保持列ID爲「1,2,3,4」而不是「1,3,4」當我刪除注意到ID 2.

因爲我用它來閱讀我的所有筆記(與BDDManager我DAO),我想不使用列表來獲取所有的筆記:

private void readAllNotes(){ 
    int i = 1; 
    Note note = new Note(); 
    BDDManager.open(); 

    do{ 
     note = BDDManager.getNoteWithId(i); 

      if(note != null){ 
       addCard(note); //here I add the note to a new TextView 
       i++; 
      } 

    }while(note != null); 

     BDDManager.close(); 
} 

而且當我刪除筆記後,我無法閱讀刪除的ID後,因爲它返回並停止讀取筆記後刪除筆記

這是我如何刪除筆記:

public int removeNoteWithId(int id){ 

    return bdd.delete(TABLE_NOTE, COL_ID + " = " +id, null); 
} 

回答

2

首先,做這樣的事情的時候,我的第一直覺是,你應該鎖定表。其次,你可以使用你的DAO循環遍歷所有的筆記,並讓每個筆記自己更新(或者打電話給DAO)。

public int removeNoteWithId(int id){ 
    for(Note n : notes) 
    { 
     n.decrementID();//OR decrement(n.getID); 
    } 
    return bdd.delete(TABLE_NOTE, COL_ID + " = " +id, null); 
} 

另外,不要一直更改id,而應該考慮有一個額外的位置排序列。這樣你就可以使用id來確保唯一性和索引,並使用另一列進行排序。

1

主鍵在創建後可能無法更改。你爲什麼不試圖使用SELECT * FROM TABLE_NOTE;?根據你的邏輯得到結果調用addcard(note)後。

0

抱歉長答覆,晚上這裏(法國)

最後我不喜歡bean5說。 而我是一個小白:對 我只是在尋找的東西「自動」,也許避免了一些I/O數據庫

private void updateAllId(int id){ 

    Note note = new Note(); 

    do{ 

     note = getNoteWithId(id+1); 
     if(note != null){ 

      note.setId(id); 
      updateNoteId(id++, note); 

     } 

    }while(note != null); 

} 

public int updateNoteId(int id, Note note){ 

    ContentValues values = new ContentValues(); 

    values.put(COL_ID, note.getId()); 

    return bdd.update(TABLE_NOTE, values, COL_ID + " = " +id, null); 

} 

謝謝大家!解決問題