Warung Bebas

Kamis, 06 Mei 2010

Be Careful With Content Providers

The notion of a Content Provider is central to getting things done in an Android application. This is the mechanism used to expose many of a device's data resources for retrieval and update: Contacts, media store, bookmarks, phone-call log, and so on. It’s hard to find an interesting Android app that doesn’t either use or implement (or both) a Content Provider.

There’s nothing magical or terribly surprising about Content Providers - you address them by Url, query them with SQL, and iterate them with a Cursor. They do what they say they do and get out of the way and they’re easy to create and use. But there’s a common anti-pattern, a way to misuse them that can potentially get your app into trouble, and maybe we’ve made it a little too easy.

The Content Providers that the Android framework gives you are described in the SDK’s android.provider package summary. For many of them, the framework provides helper classes of one sort or another, to help automate common chores and provide symbolic names for useful constants.

The problem is, there are more Content Providers in the system than are documented in that package, and while you can use them, you probably shouldn’t. They’re there because some of the Google-provided apps use them internally to access their own data resources. Because Android is an open-source project, it’s easy enough to find them just by running shell commands like find and grep over the source tree.

(By the way, searching the source tree like this is an excellent idea, something that probably every serious developer does regularly. Not 100% sure of the best way to write code to display a record from the Contacts database? Go ahead, have a look at how the built-in app does it; even better, steal some code; it’s perfectly legal.)

Back to Content Providers. For example, there’s one inside the built-in Messaging (A.K.A. texting or SMS) app that it uses to display and search your history. Just because it’s there doesn’t mean you should use it. The Android team isn’t promising that it’ll be the same in the next release or even that it’ll be there in the next release.

It’s worse than that; someone could ship an Android device based on the current SDK that follows all the rules but has its own enhanced messaging application that doesn’t happen to have such a Content Provider. Your app will break on such a device and it’ll be your fault.

So, go ahead and look at the undocumented Content Providers; the code is full of good ideas to learn from. But don’t use them. And if you do, when bad things happen you’re pretty well on your own.

0 komentar em “Be Careful With Content Providers”

Posting Komentar

 

Android OS Copyright © 2012 Fast Loading -- Powered by Blogger