Android ContentObserver用于单行更改

时间:2014-06-25 07:26:16

标签: android android-contentprovider android-contentresolver

我想为我应用的本地表写一个ContentObserver。我也有ContentProvider来访问该表。现在在我的一个Activity中,我必须观察该表中只有一行的变化。我有主键可以观察它,但主键是TEXT而不是INTEGER。当用Google搜索时,我发现使用ContentUris.withAppendedId方法获取特定行Uri。但它要求id必须是long(NUMBER)。那么当id为Uri时,有没有办法获得表格中单行的TEXT

1 个答案:

答案 0 :(得分:0)

从@pskink的评论中我找到了实现它的方法,并希望分享它。在现有的内容提供商的uri匹配器中,我们必须添加' / *'新条目如下......

private static final String AUTH = "com.test.Provider";

public static final Uri TABLE_URI = Uri.parse("content://" + AUTH + "/"
        + TABLE_NAME);
public static final Uri TABLE_ID_URI = Uri.parse("content://" + AUTH
        + "/" + TABLE_NAME + "/*");

final static int TABLE_COMMENT = 10;
final static int TABLE_ROW_COMMENT = 11;

uriMatcher.addURI(AUTH, TABLE_NAME, TABLE_COMMENT);
uriMatcher.addURI(AUTH, TABLE_NAME + "/*", TABLE_ROW_COMMENT);

在查询方法中如下......

@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String orderBy) {
db = dbManager.getReadableDatabase();

Cursor cursor = null;

switch (uriMatcher.match(uri)) {
 case TABLE_COMMENT:
     cursor = db.query(TABLE_NAME, projection, selection,selectionArgs, null, null, orderBy);
     if (cursor != null)
     cursor.setNotificationUri(getContext().getContentResolver(),uri);
     break;

case TABLE_ROW_COMMENT:
    String id = uri.getLastPathSegment();//getting the PK
    cursor = db.query(TABLE_NAME, projection,Table._ID + "=?", new String[] { id },null, null, orderBy);
    if (cursor != null)
    cursor.setNotificationUri(getContext().getContentResolver(),uri);
    break;
    }
 return cursor;
}

从活动或片段中可以从加载器获取特定行的uri,如下所示...

Uri uri = Uri.withAppendedPath(Provider.TABLE_URI,
            "pk value");
Cursor cursor = getContentResolver().query(uri, null, null, null,
                null);

在我的情况下,我将把这个Uri用于观察者。