8 - 3 - The ContentProvider Class - Part 1 (15-24)

7
[BLANK_AUDIO] Hi, I'm Adam Porter. And this is Programming Mobile Applications for Android Handheld Systems. So far in this course we've only talked in detail about two of the four fundamental components of Android. We've talked about activities and we've talked about broadcast receivers. Well in this lesson, we'll discuss one more of these fundamental components: content providers. In Android content providers represent centralized repositories of structured data. They encapsulated different data sets and they specify and enforce permissions needed to access that data. In many ways the content provider class resembles the databases, that we talked about in the lesson on data storage. Content providers however, were specifically to allow data to be shared across different applications. Applications that want to access a particular content provider do so by using a companion class called Content Resolver. ContentResolvers present a database-style interface that lets applications read and write the data that is stored in a content provider, and it therefore, supports methods such as query, insert, update, delete and more. ContentResolvers also provide additional services such as notifying registered observers when data in the content provider changes. To use a content resolver, your application will first get a reference to the current contexts, ContentResolver, by calling the content class's getContentResolver method. And the end result is that together, the content provider and the content resolver Make it possible for code running in one process to access data managed in another process. To give some examples. Android comes with a number of standard content providers. For instance, there's a content provider that stores browser information such as your bookmarks and

description

aaaaaaaaaaaaaaaaaaaaaaaaaaa

Transcript of 8 - 3 - The ContentProvider Class - Part 1 (15-24)

[BLANK_AUDIO]Hi, I'm Adam Porter.And this is Programming MobileApplications for Android Handheld Systems.So far in this course we've only talked indetail about two of the four fundamentalcomponents of Android.We've talked about activities and we'vetalked about broadcast receivers.Well in this lesson, we'll discuss onemore of these fundamental components:content providers.In Android content providers representcentralized repositories of structureddata.They encapsulated different data sets andthey specifyand enforce permissions needed to accessthat data.In many ways the content provider classresembles the databases,that we talked about in the lesson on datastorage.Content providers however, werespecifically to allowdata to be shared across differentapplications.Applications that want to access aparticular content providerdo so by using a companion class calledContent Resolver.ContentResolvers present a database-styleinterface that lets applicationsread and write the data that is storedin a content provider, and it therefore,supportsmethods such as query, insert, update,delete and more.ContentResolvers also provide additionalservices such as notifyingregistered observers when data in thecontent provider changes.To use a content resolver, yourapplication will first get a referenceto the current contexts, ContentResolver,bycalling the content class'sgetContentResolver method.And the end result is that together,the content provider and the contentresolver Makeit possible for code running in oneprocess to access data managed in anotherprocess.To give some examples.Android comes with a number of standardcontent providers.For instance, there's a content providerthat stores browserinformation such as your bookmarks and

your browsing history.There's one for keeping track of thetelephone calls, that you make.And there's one from one managing contactinformation, there'sanother for keeping track of yourpictures, songs and videos.And yet another for keeping track of thewords you type into variousapplications So that your device can givebetter and better predictive typing overtime.And of course there are many more.Logically, the data managed by a contentprovider is represented as a databasetable.For example, a content provider formanaging a list of artists.Might have data elements or columns foreach record.For example, an ID field called _ID, andan artist name field, in this case calledartist.Applications identify the data they wantand thecontent provider who has that data througha URI.The specific content of that URIidentifies aspecific data set that's managed by aspecific ContentProvider.Let's look at that format.Content URIs start with the stringcontent://.And this is the URI's scheme and itindicates that theURI refers to data that is managed by acontent provider.Next, the URI specifies it's authoritywhich essentially namesthe specific content provider who has thedesired data.After that the URI can contain 0 or moresegmentswhich indicate the specific data setcontaining the desired data.And finally URI can have a optional idwhichwould indicate a specific record withinthe desired data set.For example, applications that want toaccess thecontacts content provider might use thefollowing URI.This URI specifies a content scheme.It specifies com.android.contacts as it'sauthority.Its path has the single string contacts,which basicallycorresponds to a logical table within the

content provider's database.And in this case, there's no ID field, sothat URI is interpreted as referringto the entire table, not to a singlerecord within the table.An application can use this URI with acontent resolver method, such as the querymethod, to retrieve some or all ofthe contact records managed by the contentprovider.As you can see, the query method takesseveralparameters, including a URI, somethinglike what we just saw,an array of strings which specifies thespecific columnswithin the database that should beretrieved from the ContentProvider.And several more strings that are used toperformthe SQL query to be processed by theContentProvider.Now these strings can be used to retrieveparticular subsets ofthe data, and to specify an orderingcriteria for the results.Let's take a look at an application thatuses this method, ourfirst example application is calledContentProvider with Cursor Adapter.This application extracts contactinformation from the contactsContentProvider.And then it displays each contact's nameand photo, if they happen to have a photo.Let's see that application in action.So, here's my device.Now I'll start the ContentProvider withCursor Adapter application.As you can see this application is nowpresentingthe names and photos of some of mycontacts.Let's look at the source code for thisapplication,so here's the application open in the IDE.Now I open the main activity.In on create the code first defines thecolumns that it would request from thecontact, ContentProvider.Now there're of course many differentpieces of data associated with eachcontact.But this application is only interested inthecontacts name and his or her thumbnailphoto.Next, the code gets a reference to tocontext's ContentResolver.And after that, the code defines a string

that it uses to filter out contactswith missing or empty names, or if theyare unstarred.Now, the code creates a string that willdefine a sorting order for the resultingdata, and that means that records will besorted in ascending order of their _IDfields.Next, the code issues a call to the querymethod.And the parameters for this call, includethe URI, which isdefined by contract class; calledContacts, the columnsto extract, the where clause to filter outspecific contacts,and the string defining the sort order.And this method returns a cursor, whichwill allowthe application to iterate over theresults of this query.And finally the code creates and sets anew adapter whichwill be used by the list view, to displaythe contact info.In this case, the adapter is a contactinfo list adapter which is defined by thisapplication.Let's open that class now.In this class's constructor, the codefinds and storesa default image for contacts that have nothumbnail photo.Now, when the List View needs views todisplay,it will first call the newView method togeta brand new view, and then it will callthe bindView method to add data to thatview.Let's look at each of these two methods,one at a time.First, the newView method gets a referenceto the LayoutInflater service.And then, it calls the inflate method tocreate the newView based on an XLMresource.Now, down in the bindView method, the codefills in that view.First, it displays the contact's namewithin a text view.And next, it stores a reference to animage view within thisview, and it stores the default photo inthe photo bitmap variable.After that, the code checks whether the isan actual photo stored for this contact.And if so, it gets the URI associated withthat photo andthen opens an input stream to read the

photo data into memory.Next, it turns that data into a bitmapwhich it stores in the photo bitmapvariable.And finally, the code sets the photobitmap.As the image bitmap for the image viewobject we saw earlier.When an application queries aContentProvider, thatoperation can take a while to complete.And as we've mentioned in other contexts,we typically want to avoid doingintensive operations on the main thread,because that can negatively affectapplication responsiveness.To prevent this from happening when weuse ContentProviders, Android provides theCursorLoader class.The CursorLoader uses an AsyncTask so thatqueries will beperformed on a background thread and noton the main thread.To use a CursorLoader, your applicationwill first needto create an object that implements theLoaderManager's LoaderCallback interface.And then, at run time, it will need tocreate and initializethe CursorLoader with the help ofthat object that implements the loadercallbacks.To do this, the application will call theLoaderManager's initLoader method tocreate and initialize a loader.That method takes several parameters,including an ID,arguments, and the object that implementsthe LoaderCallbacks.After initLoader was called, severalcallbacks will occur.The first callback will be to the onCreateloader method.In this method, we'll create and return anew loader for the specified ID.And when that loader finishes loading itsdata, Android calls the next callbackmethod, onLoadFinished.This method receives the newly createdloaderand a cursor containing the relevant data.When a previously created loader is reset,the onLoaderReset method is called.In this method, applications willtypically remove anyreferences they have to the previousloader's data.Our next example application is calledContentProviderWithCursorLoader.This application produces the same result

as our previous example.It extracts contact information from theAndroid Contacts ContentProviderand it then displays each contact's nameand photo if the photo is available.However, this application performs theContentProvider Queryin a background thread using theCursorLoader.Let's see that application in action.So here's my device, now I'll startup the Content Provider with Cursor LoaderApplication.And as promised we see the same data, thatwe did with the previous application.Let's take a look at the source code forthis applicationSo here's the application, open in theIDE.Now, I'll open the main activity.And so in on create, you'll see that thisapplication creates and sets an emptyadapter, because there's nodata to show at this point Next, the codegets loaderManager and then calls theinitLoader method on it.Passing in the id zero.Passing in null for the arguments.And passing in the reference this as theobject to call back as the loaderprogresses.As we said before, the first call backmethod to be called will be theon create loader method and this code setsup the same filters that we saw before.We don't want contacts with empty ormissing namesand we don't want contacts that are unstared.We also want this date to be sorted in aascending order.By I.D. And then the code creates andreturns anew CursorLoader, passing in theinformation that we just set up.The query that provides the data for thisloader will be performed on a backgroundthread.And when that query is finished, theonLoad finish method will be called.This method takes the cursor that ispassed in, andswaps in into the list adapter, used bythis application.And finally, when the cursor is about tobe closed, the onLoader reset method iscalled.In this case, that method simply swaps ina null cursor to the list view's listadapter.

[BLANK_AUDIO]