2013-08-02 44 views
1

我是新來的android開發,並遇到了刪除SQLite表中的行,我一直沒有找到解決方案的問題。當我嘗試刪除一行時,什麼都沒有發生。Android:從SQLite表中刪除一行並更新ListView

在我的活動中,名爲'MainActivity',我使用上下文菜單來調用一個方法從列表中刪除一個項目。的這部分程序如下:

case R.id.delete_program: 
DBAdapter adap = new DBAdapter(this); 
adap.open(); 
long pass = (long) (position + 1); 
adap.removeFromCurrent(pass); 
adap.close(); 

Runnable run = new Runnable() { 
    public void run(){      
     refreshCurrent(getApplicationContext()); 
    } 
}; 
runOnUiThread(run); 
proAdapt.notifyDataSetChanged(); 
    return true; 

在 '將對DBAdapter' 的方法removeFromCurrent():

public boolean removeFromCurrent(long cp_id) { 

    return this.dB.delete(PROGRAMS_TABLE, CP_ID + '=' + cp_id, null) > 0; 
} 

在 'MainActivity' 的方法refreshCurrent():

public static void refreshCurrent(Context context) {   
    CURRENT.clear(); 
    DBAdapter adap = new DBAdapter(context); 
    adap.open();   
    ArrayList<Program> temp = adap.getCurrentPrograms(); 
    for(Program item : temp) { 
     Toast.makeText(context, "Item added: " + item.getName(), Toast.LENGTH_SHORT).show(); 
     CURRENT.add(item); 
    } 
    adap.close();  
} 

我使用吐司檢查表是否已經改變,但顯示器沒有改變。 從 '將對DBAdapter' 的方法getCurrentPrograms():

public ArrayList<Program> getCurrentPrograms() { 
    ArrayList<Program> list = new ArrayList<Program>(); 

    Cursor cursor = 
      this.dB.query(PROGRAMS_TABLE, new String[] { 
        CP_ID, CP_NAME, ACTUAL_DAY, D_ID, CP_CYCLE, CP_DAY_ONE }, 
        null, null, null, null, null); 

    int rows = cursor.getCount(); 

    if(cursor != null) 
     cursor.moveToFirst();  

    for(int i = 1; i <= rows; i++) { 
     list.add(new Program(cursor.getString(cursor.getColumnIndex(CP_NAME)), 
       cursor.getInt(cursor.getColumnIndex(ACTUAL_DAY)), 
       cursor.getInt(cursor.getColumnIndex(CP_DAY_ONE)), 
       cursor.getInt(cursor.getColumnIndex(CP_CYCLE)))); 
     cursor.moveToNext(); 
    }     
    return list; 
} 

ArrayList中 '當前' 是用於填充ListView列表。我的想法是,我將能夠從表中刪除一行,然後重新填充此列表以及ListView。我也很好奇,一旦刪除了一行,SQLite表發生了什麼變化;其他的行是向上移動一個位置,還是留在同一個地方?

我對此仍然很陌生,所以對我的問題或其他代碼的提示的任何幫助將非常感激。讓我知道我的編程有什麼問題。

回答

0

如果您使用的是SQLiteOpenHelper你應該得到一個SQLiteDatabase對象,然後使用事務,如果你不把它設置爲成功,那麼什麼都不會發生

SQLiteDatabase db = mDbHelper.getWritableDatabase(); 
db.beginTransaction(); 
//Do stuff 
db.setTrasactionSuccessfull(); 
db.endTransaction(); 

而且我認爲當你傳遞null進入where子句where無關緊要。

你應該有類似db.delete("tbl", "id=?", new String[]{String.valueOf(id)});

+0

我想通了我的代碼有什麼問題;我沒有正確理解自動增量如何工作。我的印象是,通過刪除一行,上面的所有行都會減1。這讓我相信我能夠擁有一個與我的表中的行ID相對應的數組列表。你知道我的原始信念可以實現嗎? –

+1

這樣做會違背數據庫的原則,行標識在整個生命週期中都是唯一的,爲什麼不將數據填充到某種類型的HashMap或Dictionary類型的東西中? – FabianCook