3

我有一个 SQLite 数据库的内容提供程序,它有多个表并使用如下 URI:

Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);

这似乎是标准模式,1 个 URI 到 1 个数据库表,所有行都有 1 个 CONTENT_TYPE,单行有 1 个。

但是,我需要为表数据的子集提供 URI。目前向我的数据库中添加大量附加表对我来说没有意义。看起来内容提供者似乎是为了处理这个问题而设计的,我只是看不到它。基本上我想要一个指向查询而不是表的 URI。希望这是有道理的。

4

1 回答 1

4

您只需添加应用程序所需的新 URI,然后修改内容提供者的查询方法:

public class ExampleProvider extends ContentProvider {

    private static final UriMatcher sUriMatcher;


    sUriMatcher.addURI("com.example.app.provider", "table3", 1);
    sUriMatcher.addURI("com.example.app.provider", "table3/#", 2);
    sUriMatcher.addURI("com.example.app.provider", "table3/customquery", 3);

public Cursor query(
    Uri uri,
    String[] projection,
    String selection,
    String[] selectionArgs,
    String sortOrder) {

    switch (sUriMatcher.match(uri)) {


        // If the incoming URI was for all of table3
        case 1:

            if (TextUtils.isEmpty(sortOrder)) sortOrder = "_ID ASC";
            break;

        // If the incoming URI was for a single row
        case 2:

            /*
             * Because this URI was for a single row, the _ID value part is
             * present. Get the last path segment from the URI; this is the _ID value.
             * Then, append the value to the WHERE clause for the query
             */
            selection = selection + "_ID = " uri.getLastPathSegment();
            break;
        case 3:
             // handle your custom query here

             break;

    }
    // call the code to actually do the query
}
于 2012-05-12T22:47:06.347 回答