一、ContentProvider介绍

来源:互联网 发布:工艺角 知乎 编辑:程序博客网 时间:2024/05/18 17:43


 

ContentProvider翻译为“内容提供者”;

定义:指该应用包含一些方法,供外界访问,其他应用程序可以调用该方法,比如如果应用A创建了一个数据库“test.db”,默认是私有的,即其他应用程序不能对其进行操作,但是如果应用A使用了ContentProvider,则其他应用程序可以访问该数据库;

用途:某个应用对外共享数据;

注意点:和Activity一样,都是Android 的Component之一,如果要创建,则需要在AndroidManifest.xml中设置;

好处:提供了统一的insert,update,delete,query方法,操作任何数据;

 

二、URI介绍

 

URI:类似于我们以前使用的URI,但是此处URI的目的是为了能够根据URI以及调用的方法来决定怎样操作数据,比如:

uri="..../person",调用insert方法,则表示需要插入一条person记录;

ContentProvider中使用的URI注意点:

(1)以  content://   开头;

(2)模式为:content://authorities/path;其中authorities类似于域名或IP,用来标识操作哪个ContentProvider,path表示具体的操作;

举例:

content://org.xiazdong.providers.personprovider/person 表示调用“org.xiazdong.providers.personprovider”的方法,操作person数据;

 

补充:ContentUris辅助类

 

URI uri = ContentUris.withAppendId(URI param,int id);  //为某个URI添加一个ID

比如param = "content://authorities/person",id=10,则uri = "content://authorities/person/10";

long id = ContentUris.parseId(URI uri); //提取URI中最后的ID

比如uri = "content://authorities/person/10",则返回的id=10;

 

三、ContentProvider开发步骤简要说明

 

1.创建一个类,并继承ContentProvider,比如PersonProvider;

2.在AndroidManifest.xml中设置:

<provider android:name=".PersonProvider" android:authorities="org.xiazdong.provides.personprovider"/>

3.定义UriMatcher,

private UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);  //创建一个URI匹配器,参数为不匹配时的返回值

在onCreate中使用matcher.addURI("authorities","path",code);  //加入匹配的URI,如果匹配,则matcher.match(uri)返回code;

如果要匹配:content://authorities/path/数字  ,则matcher.addURI("authorites","path/#",code);

4.重写:

onCreate():用于为操作数据做准备;

insert:插入数据,返回插入的记录所代表的URI;

update:更新数据,返回操作影响的记录行数;

delete:删除数据,返回操作影响的记录行数;

query:查询数据,返回Cursor;

getType:记录的类型,如果操作集合,则必须以vnd.android.cursor.dir开头,如果操作非集合,则必须以vnd.android.cursor.item开头,比vnd.android.cursor.dir/person

5.外部调用:

ContentResolver resolver = this.getContext().getContentResolver();

resolver.insert();

resolver.update();

resolver.delete();

resolver.query();

 

四、应用实例

 

AndroidManifest.xml

[html] view plain copy
  1. <provider  
  2.             android:name=".PersonProvider"  
  3.             android:authorities="org.xiazdong.provides.personprovider"              
  4.             ></provider>  

 

PersonProvider.Java

[java] view plain copy
  1. package org.xiazdong.db;  
  2.   
  3. import android.content.ContentProvider;  
  4. import android.content.ContentUris;  
  5. import android.content.ContentValues;  
  6. import android.content.UriMatcher;  
  7. import android.database.Cursor;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9. import android.net.Uri;  
  10.   
  11. public class PersonProvider extends ContentProvider{  
  12.     private DatabaseHelper helper;  
  13.     private SQLiteDatabase db;  
  14.     private UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);  
  15.     @Override  
  16.     public boolean onCreate() {  
  17.         helper = new DatabaseHelper(this.getContext());  
  18.         //匹配:content://org.xiazdong.provides.personprovider/person,返回值为1  
  19.         matcher.addURI("org.xiazdong.provides.personprovider""person"1);  
  20.         //匹配:content://org.xiazdong.provides.personprovider/person/数字,返回值为2  
  21.         matcher.addURI("org.xiazdong.provides.personprovider""person/#"2);  
  22.         return true;  
  23.     }  
  24.   
  25.     @Override  
  26.     public Cursor query(Uri uri, String[] projection, String selection,  
  27.             String[] selectionArgs, String sortOrder) {  
  28.         db = helper.getWritableDatabase();  
  29.         switch(matcher.match(uri)){  
  30.         case 1//查询所有记录  
  31.             return db.query("person", projection, selection, selectionArgs, nullnullnull);  
  32.         case 2://查询特定记录  
  33.             long id = ContentUris.parseId(uri);  
  34.             String where = "id="+id;  
  35.             if(selection!=null&&!"".equals(selection)){ //因为selection可能还包含其他的where语句,需要再加上 "and id=?"  
  36.                 where = where + " and "+selection;  
  37.             }  
  38.             return db.query("person", projection, where, selectionArgs, nullnullnull);  
  39.         default:  
  40.             throw new IllegalArgumentException("wrong uri");  
  41.         }  
  42.     }  
  43.     /* 
  44.      * 如果操作集合,则必须以vnd.android.cursor.dir开头 
  45.      * 如果操作非集合,则必须以vnd.android.cursor.item开头 
  46.      * */  
  47.     @Override  
  48.     public String getType(Uri uri) {  
  49.         switch(matcher.match(uri)){  
  50.         case 1:  
  51.             return "vnd.android.cursor.dir/person";  
  52.         case 2:  
  53.             return "vnd.android.cursor.item/person";  
  54.         }  
  55.     }  
  56.     /* 
  57.      * values为插入的数据 
  58.      * 返回:插入的数据所代表的URI 
  59.      * */  
  60.     @Override  
  61.     public Uri insert(Uri uri, ContentValues values) {  
  62.         db = helper.getWritableDatabase();  
  63.         switch(matcher.match(uri)){  
  64.         case 1:  
  65.             long rowid = db.insert("person"null, values);  
  66.             return ContentUris.withAppendedId(uri, rowid);  //返回插入的记录所代表的URI  
  67.         default:  
  68.             throw new IllegalArgumentException("wrong uri");  
  69.         }  
  70.     }  
  71.     @Override  
  72.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  73.         db = helper.getWritableDatabase();  
  74.         switch(matcher.match(uri)){  
  75.         case 1:return db.delete("person", selection, selectionArgs);  
  76.         case 2//删除特定id记录  
  77.             long id = ContentUris.parseId(uri);  
  78.             String where = "id="+id;  
  79.             if(selection!=null&&!"".equals(selection)){  
  80.                 where  += " and "+selection;  
  81.             }  
  82.             return db.delete("person", where, selectionArgs);  
  83.         default:  
  84.             throw new IllegalArgumentException("wrong uri");  
  85.         }  
  86.     }  
  87.     @Override  
  88.     public int update(Uri uri, ContentValues values, String selection,  
  89.             String[] selectionArgs) {  
  90.         db = helper.getWritableDatabase();  
  91.         switch(matcher.match(uri)){  
  92.         case 1:return db.update("person", values, selection, selectionArgs);  
  93.         case 2//更新特定id记录  
  94.             long id = ContentUris.parseId(uri);  
  95.             String where = "id="+id;  
  96.             if(selection!=null&&!"".equals(selection)){  
  97.                 where  += " and "+selection;  
  98.             }  
  99.             return db.update("person", values,where, selectionArgs);  
  100.         default:  
  101.             throw new IllegalArgumentException("wrong uri");  
  102.         }  
  103.     }  
  104. }  

以下我们创建一个测试类:

 

ContentProviderTest.java

 

[java] view plain copy
  1. package org.xiazdong.db.test;  
  2.   
  3. import org.xiazdong.db.domain.Person;  
  4.   
  5. import android.content.ContentResolver;  
  6. import android.content.ContentValues;  
  7. import android.database.Cursor;  
  8. import android.net.Uri;  
  9. import android.test.AndroidTestCase;  
  10. import android.util.Log;  
  11.   
  12. public class ContentProviderTest extends AndroidTestCase{  
  13.     public void testInsert()throws Exception{   //插入"name=yyy,age=100"的记录  
  14.         Uri uri = Uri.parse("content://org.xiazdong.provides.personprovider/person");  
  15.         ContentResolver resolver = this.getContext().getContentResolver();  
  16.         ContentValues values = new ContentValues();  
  17.         values.put("name""yyy");  
  18.         values.put("age"100);  
  19.         resolver.insert(uri, values);  
  20.     }  
  21.     public void testUpdate()throws Exception{   //更新id=5的记录为name=yyy,age=100  
  22.         Uri uri = Uri.parse("content://org.xiazdong.provides.personprovider/person/5");  
  23.         ContentResolver resolver = this.getContext().getContentResolver();  
  24.         ContentValues values = new ContentValues();  
  25.         values.put("name""yyy");  
  26.         values.put("age"100);  
  27.         resolver.update(uri, values, nullnull);  
  28.     }  
  29.     public void testDelete()throws Exception{   //删除id=11的记录  
  30.         Uri uri = Uri.parse("content://org.xiazdong.provides.personprovider/person/5"); //删除id=11的记录  
  31.         ContentResolver resolver = this.getContext().getContentResolver();  
  32.         resolver.delete(uri, nullnull);  
  33.     }  
  34.     public void testQuery()throws Exception{    //插入全部记录并显示  
  35.         Uri uri = Uri.parse("content://org.xiazdong.provides.personprovider/person");   //查询所有记录  
  36.         ContentResolver resolver = this.getContext().getContentResolver();  
  37.         Cursor cursor = resolver.query(uri, nullnullnullnull);  
  38.         while(cursor.moveToNext()){  
  39.             Person person = new Person(cursor.getInt(cursor.getColumnIndex("id")),cursor.getString(cursor.getColumnIndex("name")),cursor.getInt(cursor.getColumnIndex("age")));  
  40.             Log.v("ContentProvider", person.toString());  
  41.         }  
  42.     }  
  43. }  
0 0