使用 ContentProvider 插入新数据时应用程序崩溃

App crashes when insert new data with ContentProvider

这是代码:

对于 ContentProviderinsert

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);

注意:所有常量都在合同中定义class。

你忘了return:

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

说明:switch遍历所有case,最后默认。我们应该在 case 语句中调用 break 或 return。