stanna stanna - 2 days ago 5
Android Question

Trouble understanding UriMatcher Syntax

I've done a lot of reading on the subject but I can't find anything on what these symbols,

*, #
, are meant to be/represent.

If they're used as a placeholder for something, like SqLite's
?
, then what are they replacing? Also, if all you're doing is matching Uri's, then whats the purpose of having this cryptic notation?

If I wanted to return a list, object or anything else, why wouldn't I just name the constant with something readable and give it an arbitrary value and go on from there?

E.g.

sURIMatcher.addURI("contacts", "people", PEOPLE);
sURIMatcher.addURI("contacts", "people/#", PEOPLE_ID);
sURIMatcher.addURI("contacts", "people/#/phones", PEOPLE_PHONES);


into

sURIMatcher.addURI("contacts", "people", PEOPLE);
sURIMatcher.addURI("contacts", "people_id", PEOPLE_ID);
sURIMatcher.addURI("contacts", "people_phones", PEOPLE_PHONES);

Answer

I use this for example to delete an entry of my database with a specific id.

Uri deleteUri = Uri.parse(NoteProvider.CONTENT_URI + "/" + id);
context.getContentResolver().delete(deleteUri, null, null);

// URI Matcher
sURIMatcher.addURI(AUTHORITY, NOTE_BASE_PATH + "/#", NOTE_WITH_ID);

// delete
String id = uri.getLastPathSegment();
rowsDeleted = db.delete(NoteEntry.TABLE_NAME, NoteEntry._ID + "=" + id, null);
  • *: Matches a string of any valid characters of any length.
  • #: Matches a string of numeric characters of any length.

An URI represents a path to a resource and that is what you access with an ContentProvider. So I think that URI is best suited in this case.

A content URI is a URI that identifies data in a provider. Content URIs include the symbolic name of the entire provider (its authority) and a name that points to a table or file (a path). The optional id part points to an individual row in a table.

Comments