2012-11-08 114 views
0

我正在使用ContentProvider插入數據到SQLiteDatabase中,插入失敗。我希望有人會看到我做錯了什麼。這裏是我的代碼:插入失敗與ContentProvider

public Uri insert(Uri uri, ContentValues values) { 
    int uriType = sURIMatcher.match(uri); 
    if (uriType != ALLDATA) { 
     throw new IllegalArgumentException("Invalid URI for insert"); 
    } 
    SQLiteDatabase sqlDB = mDB.getWritableDatabase(); 
    try { 
     long newID = sqlDB.insertOrThrow(TABLE_BASEPATH, 
       null, values); 
     if (newID > 0) { 
      Uri newUri = ContentUris.withAppendedId(uri, newID); 
      getContext().getContentResolver().notifyChange(uri, null); 
      return newUri; 
     } else { 
      throw new SQLException("Failed to insert row into " + uri); 
     } 
    } catch (SQLiteConstraintException e) { 
     Log.i(DEBUG_TAG, "Ignoring constraint failure."); 
    } 
    return null; 
} 

MDB是被設置爲這樣一個全局變量:

private SQLData mDB; 

SQLDATA是我的數據庫類的名稱。當我在調試器中關注這段代碼時,它會驗證newID是否大於0並進入if塊。前兩行執行(賦值newUri和getContext()等),但代碼跳到底部並返回null,而不是返回newUri。有誰知道爲什麼?我看過this thread,但它似乎不適用於我的情況。提前致謝!

回答

1

我想我以前有過這個,它可以是兩件事情。

首先,它取決於調試器。我確信我已經有了它的代碼已經通過返回的地方;語句正確,只假裝跳轉到返回null。

檢查調用函數。

其次,通常是我的情況的罪魁禍首。您在舊版本的編譯代碼上運行調試器。即運行調試清理。我不記得確切的原因,我只知道我有這個確切的情況。

+2

其實它可能是很多事情,但這些是兩個我先檢查。同時檢查notifyChange是否觸發某種後續調用。 – Emile

+0

你是對的,埃米爾。調用函數確實返回一個非空Uri。奇怪的。所以那不是我的問題。謝謝! – Melanie