How to create a content provider URI for a row of a table, not a complete table

I have a content provider for a SQLite database that has multiple tables and uses a URI as follows:

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

This seems to be a standard template, with 1 URI table in 1 database, along with 1 CONTENT_TYPE for all rows and 1 for one row.

However, I need to have a URI for subsets of tabular data. Currently, it makes no sense for me to add a ton of additional tables to my database. It seems that the content provider is designed to handle this, I just don't see it. Basically I want to have a URI that points to a query instead of a table. Hope this makes sense.

+3
source share
1 answer

, 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
}
+4

All Articles