2017-07-25 70 views
0

此代碼插入新的數據:應用程序崩潰時的ContentProvider

對於insertContentProvider的:

public Uri insert(Uri uri, ContentValues contentValues) { 

    final int match = sUriMatcher.match(uri); 
    switch (match) { 
     case DOG: 
      insertDog(uri, contentValues); 
     default: 
      throw new IllegalArgumentException("Insertion is not supported for " + uri); 
    } 
} 

private Uri insertDog(Uri uri, ContentValues contentValues) { 

    SQLiteDatabase db = mDbHelper.getWritableDatabase(); 
    long id = db.insert(DogEntry.TABLE_NAME, null, contentValues); 
    if (id == -1) { 
     Log.e(LOG_TAG, "Failed to insert row for " + uri); 
     return null; 
    } 
    return ContentUris.withAppendedId(uri, id); 
} 

這是我插入數據:

ContentValues values = new ContentValues(); 
    values.put(DogEntry.NAME, "Doggy"); 
    values.put(DogEntry.BREED, "Dingo"); 
    values.put(DogEntry.GENDER, DogEntry.GENDER_MALE); 
    values.put(DogEntry.WEIGHT, 15); 
    Uri newUri = getContentResolver().insert(DogEntry.CONTENT_URI,values); 

注意:所有常數在合同類中定義。

+2

「應用程序崩潰」 - 使用LogCat檢查與您的崩潰相關的Java堆棧跟蹤:https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-這 – CommonsWare

+0

@CommonsWare,它說插入不支持的URI。該URI是300%正確的。所以呢? –

+0

你有沒有運行一次,並改變你的數據庫模式,在這種情況下,你需要重新安裝你的應用程序。 –

回答

4

你忘了回報:

... 
case DOG: 
    return insertDog(uri, contentValues); 

說明:開關經過在結束所有的情況下和默認。我們應該在案件陳述中打破或返回。

+0

你一定是個天才。有用。謝謝。 –