从contentProvider.update()更改uri的notifyChange

Sha*_*wat 6 sqlite android android-contentprovider contentobserver

我已经实现update()ContentProvider,并使用通知给观察者getContext().getContentResolver().notifyChange(uri, null);

我显而易见的需要是,每当只有一行生效时我想用行特定的uri通知,但是找不到这样做的方法.一个额外的查询就像"select id where selectionArgs"可以做到这一点,但这将是一个愚蠢的方式.

onchange(boolean, uri)得到完整的uri而不是特定的行,容易理解这是因为ContentProvider.update()发送相同.

some code for more clarity
Run Code Online (Sandbox Code Playgroud)

MyContentProvider的update()方法

 @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

        Log.d("TAG", "update " + uri.getPath());

        int count = 0;
        switch (uriMatcher.match(uri)) {
        case BOOKS:
            count = booksDB.update(DATABASE_TABLE, values, selection, selectionArgs);
            break;
        case BOOK_ID:
            count = booksDB.update(DATABASE_TABLE, values,
                    _ID + " = " + uri.getPathSegments().get(1)
                            + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (count == 1) {
            Cursor c = query(uri, new String[] { _ID }, selection, selectionArgs, null);
            long rowId = Long.valueOf(c.getString(c.getColumnIndex(_ID)));
            uri = ContentUris.withAppendedId(CONTENT_URI, rowId);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;

    }
Run Code Online (Sandbox Code Playgroud)

我会更新表格的一些方式

getContentResolver().update(MyContentProvider.CONTENT_URI, values1, MyContentProvider._ID+"<?", new String[]{"3"}));
Run Code Online (Sandbox Code Playgroud)

坦率地说,代码几乎与问题无关,只是试图给你一些背景信息

Bru*_*nto 8

在您的provider方法中,只需返回附加了id的URI

@Override
public Uri insert(Uri uri, ContentValues values) {
    Log.i(TAG, "insert " + uri);
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = URI_MATCHER.match(uri);

    Uri returnUri;
    switch (match) {
        case MESSAGE: {
            long _id = db.insert(MessageContract.MessageEntry.TABLE_NAME, null, values);
            if (_id > 0)
                returnUri = ContentUris.withAppendedId(MessageContract.MessageEntry.CONTENT_URI, _id);
            else
                throw new android.database.SQLException("Failed to insert row into " + uri);
            break;
        }

        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    getContext().getContentResolver().notifyChange(returnUri, null);


    return returnUri;
}
Run Code Online (Sandbox Code Playgroud)

并为观察者注册真实的后代.

getContentResolver().registerContentObserver(MessageContract.MessageEntry.CONTENT_URI, true, mContentObserver);
Run Code Online (Sandbox Code Playgroud)

要从Uri获取id,您可以使用 ContentUris.parseId(uri)