0

我已经创建了自己的 ContentProvider,但我不确定如何检索它。调用 getType 方法时,我不断得到一个空值。

这是我的代码:
CurrentPlacesMetaData 类:

public static final String AUTHORITY = "healthcare.management.elderly.providers.CurrentPlacesContentProvider";
public static final String CONTENT_TYPE_PLACES_LIST = "vnd.android.cursor.dir/vnd.healthcare.places";
public static final String CONTENT_TYPE_PLACES_ONE = "vnd.android.cursor.dir/vnd.healthcare.places#";

CurrentPlacesContentProvider 类:

public static final Uri CONTENT_URI = Uri.parse("content://" 
        + CurrentPlacesMetaData.AUTHORITY + "/currentplaces");
static {
     sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
     sUriMatcher.addURI(CurrentPlacesMetaData.AUTHORITY, "places", PLACES_TYPE_LIST);
     sUriMatcher.addURI(CurrentPlacesMetaData.AUTHORITY, "places/#", PLACES_TYPE_ONE);
}
@Override
public String getType(Uri uri) {
    switch(sUriMatcher.match(uri)) {
        case PLACES_TYPE_LIST:
            return CurrentPlacesMetaData.CONTENT_TYPE_PLACES_LIST;
        case PLACES_TYPE_ONE:
            return CurrentPlacesMetaData.CONTENT_TYPE_PLACES_ONE;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
    }
}

尝试调用 ContentProvider 的方法:

Uri uri = Uri.parse("content://healthcare.management.elderly.providers.CurrentPlacesContentProvider/currentplaces/places");
String str = context.getContentResolver().getType(uri)

我为 str 得到一个空值,这可能表明 uri 未被识别。那么我哪里出错了?提前致谢!

4

2 回答 2

1

您的 URI 包含currentplaces在您正在匹配的 uri 匹配器中作为最后一部分 places

您可以使用以下格式进行内容提供者的 uri 匹配

private static final String AUTHORITY = "xxxxxxxxxxxxx";
private static final String COMMENT_BASE_PATH = "comment";

private static final int COMMENT = 100;
private static final int COMMENT_ID = 101;


public static final Uri URI_COMMENT = Uri.parse("content://" + AUTHORITY + "/" + COMMENT_BASE_PATH);

private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
    sURIMatcher.addURI(AUTHORITY, COMMENT_BASE_PATH , COMMENT);
    sURIMatcher.addURI(AUTHORITY, COMMENT_BASE_PATH + "/*" , COMMENT_ID);
}

然后你可以参考 URI_COMMENT 任何你喜欢的地方。

于 2012-08-09T05:47:11.460 回答
1

您可以使用以下方法调用 ContentProvider,

Cursor c = managedQuery(uri, null, null, null, null);

但是现在不推荐使用 managedQuery ,您必须使用CursorLoader. 这是一个使用CursorLoader.

于 2012-08-09T05:30:42.163 回答