how to decide between direct database access and content provider?

前端 未结 3 1200
时光取名叫无心
时光取名叫无心 2020-12-29 08:15

I am writing an application that consists of business logic and UI parts. There is quite big amount of data to be stored and accessed/modified by both BL and UI. In most of

3条回答
  •  暖寄归人
    2020-12-29 08:18

    I would recommend spending that extra time and energy to write your ContentProvider. ContentProviders are not just about sharing access to data. The advantages

    • You have ways of listening to your data via ContentObservers
    • ContentProviders by themselves are not thread-safe, but it is easy to implement thread-safetly
    • Cursors can be asked to keep themselves up-to-date via the ContentProvider's notifyChange
    • You can add good abstraction without affecting your business layer. Here's an example: You use the Android contacts in your application. Tomorrow you plan on introducing your own contacts (via your own WebService). The ContentProvider can be modified to assimilate this requirement in a very graceful manner.
    • JOIN tables can be exposed very well by a nice design without cluttering your business-logic code. Check out some of the Android ContentProvider like the MediaStore or the ContactsContract. Check out their CONTENT_URI definitions

    All in all, a ContentProvider is a very beautiful Android concept which is well-worth implementing. And once you have your definitions in place, it is not very difficult to add support for more data. It will then be as easy as writing your database code in a Helper class or your business-logic classes.

    ** EDIT ** Here's a utility which generates content provider code from model classes: https://code.google.com/p/mdsd-android-content-provider/

提交回复
热议问题