天天看點

android Content Provider

内容提供者即content provider,content provider提供了一個接口用來共享自己的資料,包括自己的私有資料。其他程式通過content resolve來使用這些資料。

當應用需要通過contentprovider對外共享資料時,第一步需要建立一個類繼承contentprovider并重寫下面方法:

public class personcontentprovider extends contentprovider{

      public boolean oncreate()

      public uri insert(uri uri, contentvalues values)

      public int delete(uri uri, string selection,string[] selectionargs)

      public int update(uri uri, contentvalues values, stringselection, string[] selectionargs)

     public cursor query(uri uri, string[] projection, stringselection, string[] selectionargs, string sortorder)

     public string gettype(uri uri)

}

第二步需要在androidmanifest.xml使用<provider>對該content provider進行配置,為了能讓其他應用找到該content provider , content provider采用了authorities(主機名/域名)對它進行唯一辨別,内容可以設定任意字元,為了使用友善,一般格式為:com.xxx.xxx.yyy(yy為自己設定的contentprovider名稱),以後其他程式的content resolve就通過authorities去通路這個程式的資料,name的含義與配置activity時的含義一樣,由于指定建立的繼承contentprovider類的完整類名:

<manifest .... >

   <application android:icon="@drawable/icon"android:label="@string/app_name">

       <providerandroid:name=".personcontentprovider"android:authorities="cn.itcast.providers.personprovider"/>

   </application>

</manifest>

我們執行完第二步的在androidmanifest.xml中注冊的操作後,開始書寫第一步中我們建立的類(繼承自contentprovider類)的具體代碼了:

比如其他程式要通過contentprovider執行該程式資料庫的查詢(query)操作,我們則要在該程式中覆寫接下來的query()方法,見下圖:

接下來覆寫query()方法:

之後就可以在其他應用程式中通過contentresolve來對該程式中資料庫進行查詢操作了:

這是查詢操作,“增”、“删”、“改”的代碼就可以仿照書寫了。