Search code examples
androidandroid-contentprovider

Confusion in ContentPorvider's CRUD operations


I am new to contenProvider and am reading a tutorial on how to do CRUD operations on UserDictionary.

For Query:

resolver.query(UserDictionary.Words.CONTENT_URI, projection, null, null, null);

For insert:

resolver.insert(UserDictionary.Words.CONTENT_URI, values); //ContentValues values = new ContentValues();

For update:

Uri uri = ContentUris.withAppendedId(Words.CONTENT_URI, id);
long noUpdated = resolver.update(uri, values, null, null);

for delete:

long noDeleted = resolver.delete(Words.CONTENT_URI,
   Words.WORD + " = ? ", new String[]{"Zaphod"});

My confusion is in update and delete operations.

In update: why is it using Words.CONTENT_URI in withAppendedId() ? shouldn't it be using UserDictionary.Words.CONTENT_URI ?

Also in delete: its not using withAppendedId(). Still why is it using Words.CONTENT_URI ?


Solution

  • In your example UserDictionary.Words.CONTENT_URI is what identifies the data in a provider, so the data location, the appended Id is what identifies a unique record.

    So, by your examples:

    1) For Query, is using UserDictionary.Words.CONTENT_URI to return all the records under this content Uri address. If you wanted to return only one specific record, from which you already know its Id, then it could also be as follows:

    Uri uri = ContentUris.withAppendedId(Words.CONTENT_URI, id);
    resolver.query(uri, projection, null, null, null); 
    

    3) For Insert, no Id is used because the record doesn't exist yet. What the operation does is to insert a new record into the database, and the return value will be the new record Uri, which will include the new Id.

    3) For Update, the appended Id is used to identify which specific record must be updated. Updating UserDictionary.Words.CONTENT_URI without a record Id would result in the update of all the records.

    4) For Delete, your example is deleting all the records where the column Words.WORD has the value "Zaphod", which may result in 0, 1, or multiple records being deleted. If you wanted to delete only 1 specific record from which you know its Id, then it would be as next:

    Uri uri = ContentUris.withAppendedId(Words.CONTENT_URI, id);
    resolver.delete(uri, null, null);
    

    Answering your last question, there is no difference between Words.CONTENT_URI and UserDictionary.Words.CONTENT_URI. The UserDictionary section is a qualifier, which can be removed if has been added as an import on top of the java file, this allows not having to type it all the time, but at the end both are actually the same thing and makes no difference.