A (175)

(Tuis.) #1

548 CHAPTER 14: Android Content Providers: Providing Data to Applications


Once the viceroyContact ContentValues object has once again been fully loaded for use, you
will again use the getContentResolver( ).insert( ) method call chain to insert this viceroyContact
ContentValues object into the Data database using the CONTENT_URI data field. The Java code is
highlighted in Figure 14-44.


Figure 14-44. Call a getContentResolver( ).insert( ) method call chain with a viceroyContact ContentValues object


Finally, you will use another Toast.makeText( ) method call with the current Context object (this), the
electedViceroy String data, and the LENGTH_LONG constant. This will tell the user that you have
written your newly elected Viceroy’s name into the database as requested. The final code for the
entire addGalaxyViceroy( ) method is as follows:


protected void addGalaxyViceroy(String electedViceroy) {
ContentValues viceroyContact = new ContentValues();
viceroyContact.put(RawContacts.ACCOUNT_NAME, electedViceroy);
viceroyContact.put(RawContacts.ACCOUNT_TYPE, electedViceroy);
Uri newUri = getContentResolver().insert(RawContacts.CONTENT_URI, viceroyContact);
long rawContactsId = ContentUris.parseId(newUri);
viceroyContact.clear();
viceroyContact.put(Data.RAW_CONTACT_ID, rawContactsId);
viceroyContact.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
viceroyContact.put(StructuredName.DISPLAY_NAME, electedViceroy);
getContentResolver().insert(Data.CONTENT_URI, viceroyContact);
Toast.makeText(this, electedViceroy + " has been elected", Toast.LENGTH_LONG).show();
}


The code is shown in Figure 14-45, error-free, and is ready to test in the Nexus One AVD
emulator. You have written a database WRITE method using less than a dozen lines of Java code!
Congratulations!

Free download pdf