Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a content provider URI for a range of table rows, instead of full table

I have a Content Provider for a SQLite database that has multiple tables and uses URIs like so:

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

This seems to be the standard pattern, with 1 URI to 1 database table, along with 1 CONTENT_TYPE for all rows, and 1 for a single row.

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

like image 506
drod Avatar asked Sep 02 '25 16:09

drod


1 Answers

You just need to add wherever new URIs needed by your application then modify the query method of your content provider:

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
}
like image 171
Mahdi Hijazi Avatar answered Sep 05 '25 05:09

Mahdi Hijazi