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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With