contentProvider 内容提供者

http://blog.csdn.net/woshixuye/article/details/8280879

实例代码
当数据需要在应用程序间共享时,我们就可以利用ContentProvider为数据定义一个URI。之后其他应用程序对数据进行查询或者修改时,只需要从当前上下文对象获得一个ContentResolver(内容解析器)传入相应的URI就可以了。
contentProvider和Activity一样是Android的组件,故使用前需要在AndroidManifest.xml中注册,必须放在主应用所在包或其子包下。

 1  <application android:icon="@drawable/icon" android:label="@string/app_name">  
 2      <activity android:name=".MainActivity"  
 3                android:label="@string/app_name">  
 4          <intent-filter>  
 5              <action android:name="android.intent.action.MAIN" />  
 6              <category android:name="android.intent.category.LAUNCHER" />  
 7          </intent-filter>  
 8          <intent-filter>  
 9              <data android:mimeType="vnd.android.cursor.dir/person" />  
10          </intent-filter>  
11          <intent-filter>  
12              <data android:mimeType="vnd.android.cursor.item/person" />  
13          </intent-filter>  
14      </activity>  
15      <!-- 配置内容提供者,android:authorities为该内容提供者取名作为在本应用中的唯一标识 -->  
16      <provider android:name=".providers.PersonProvider"   
17 android:authorities="cn.xyCompany.providers.personProvider"/>  
18  </application>  
19  
20 内容提供者和测试代码
21  

 

 

  1 package cn.xy.cotentProvider.app.providers;  
  2 import android.content.ContentProvider;  
  3 import android.content.ContentUris;  
  4 import android.content.ContentValues;  
  5 import android.content.UriMatcher;  
  6 import android.database.Cursor;  
  7 import android.database.sqlite.SQLiteDatabase;  
  8 import android.net.Uri;  
  9 import android.util.Log;  
 10 import cn.xy.cotentProvider.service.DBOpeningHelper;  
 11   
 12 /** 
 13  * contentProvider作为一种组件必须放在应用所在包或其子包下,主要作用是对外共享数据 
 14  * 测试步骤1:将本项目先部署 
 15  * 测试步骤2:调用测试方法 
 16  * @author xy 
 17  *  
 18  */  
 19 public class PersonProvider extends ContentProvider  
 20 {  
 21     private DBOpeningHelper dbHelper;  
 22   
 23     // 若不匹配采用UriMatcher.NO_MATCH(-1)返回  
 24     private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);  
 25   
 26     // 匹配码  
 27     private static final int CODE_NOPARAM = 1;  
 28     private static final int CODE_PARAM = 2;  
 29   
 30     static  
 31     {  
 32         // 对等待匹配的URI进行匹配操作,必须符合cn.xyCompany.providers.personProvider/person格式  
 33         // 匹配返回CODE_NOPARAM,不匹配返回-1  
 34         MATCHER.addURI("cn.xyCompany.providers.personProvider", "person", CODE_NOPARAM);  
 35   
 36         // #表示数字 cn.xyCompany.providers.personProvider/person/10  
 37         // 匹配返回CODE_PARAM,不匹配返回-1  
 38         MATCHER.addURI("cn.xyCompany.providers.personProvider", "person/#", CODE_PARAM);  
 39     }  
 40   
 41     @Override  
 42     public boolean onCreate()  
 43     {  
 44         dbHelper = new DBOpeningHelper(this.getContext());  
 45         return true;  
 46     }  
 47   
 48     /** 
 49      * 外部应用向本应用插入数据 
 50      */  
 51     @Override  
 52     public Uri insert(Uri uri, ContentValues values)  
 53     {  
 54         SQLiteDatabase db = dbHelper.getWritableDatabase();  
 55         switch (MATCHER.match(uri))  
 56         {  
 57             case CODE_NOPARAM:  
 58                 // 若主键值是自增长的id值则返回值为主键值,否则为行号,但行号并不是RecNo列  
 59                 long id = db.insert("person", "name", values);   
 60                 Uri insertUri = ContentUris.withAppendedId(uri, id);   
 61                 return insertUri;  
 62             default:  
 63                 throw new IllegalArgumentException("this is unkown uri:" + uri);  
 64         }  
 65     }  
 66   
 67     /** 
 68      * 外部应用向本应用删除数据 
 69      */  
 70     @Override  
 71     public int delete(Uri uri, String selection, String[] selectionArgs)  
 72     {  
 73         SQLiteDatabase db = dbHelper.getWritableDatabase();  
 74         switch (MATCHER.match(uri))  
 75         {  
 76             case CODE_NOPARAM:  
 77                 return db.delete("person", selection, selectionArgs); // 删除所有记录  
 78             case CODE_PARAM:  
 79                 long id = ContentUris.parseId(uri); // 取得跟在URI后面的数字  
 80                 Log.i("provider", String.valueOf(id));  
 81                 String where = "id = " + id;  
 82                 if (null != selection && !"".equals(selection.trim()))  
 83                 {  
 84                     where += " and " + selection;  
 85                 }  
 86                 return db.delete("person", where, selectionArgs);  
 87             default:  
 88                 throw new IllegalArgumentException("this is unkown uri:" + uri);  
 89         }  
 90     }  
 91   
 92     /** 
 93      * 外部应用向本应用更新数据 
 94      */  
 95     @Override  
 96     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)  
 97     {  
 98         SQLiteDatabase db = dbHelper.getWritableDatabase();  
 99         switch (MATCHER.match(uri))  
100         {  
101             case CODE_NOPARAM:  
102                 return db.update("person",values,selection, selectionArgs); // 更新所有记录  
103             case CODE_PARAM:  
104                 long id = ContentUris.parseId(uri); // 取得跟在URI后面的数字  
105                 String where = "id = " + id;  
106                 if (null != selection && !"".equals(selection.trim()))  
107                 {  
108                     where += " and " + selection;  
109                 }  
110                 return db.update("person",values,where,selectionArgs);  
111             default:  
112                 throw new IllegalArgumentException("this is unkown uri:" + uri);  
113         }  
114     }  
115       
116     /** 
117      * 返回对应的内容类型 
118      * 如果返回集合的内容类型,必须以vnd.android.cursor.dir开头 
119      * 如果是单个元素,必须以vnd.android.cursor.item开头 
120      */  
121     @Override  
122     public String getType(Uri uri)  
123     {  
124         switch(MATCHER.match(uri))  
125         {  
126             case CODE_NOPARAM:  
127                 return "vnd.android.cursor.dir/person";  
128             case CODE_PARAM:  
129                 return "vnd.android.cursor.item/person";  
130             default:  
131                 throw new IllegalArgumentException("this is unkown uri:" + uri);  
132         }  
133     }  
134   
135     @Override  
136     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)  
137     {  
138         SQLiteDatabase db = dbHelper.getReadableDatabase();  
139         switch (MATCHER.match(uri))  
140         {  
141             case CODE_NOPARAM:  
142                 return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);  
143             case CODE_PARAM:  
144                 long id = ContentUris.parseId(uri); // 取得跟在URI后面的数字  
145                 String where = "id = " + id;  
146                 if (null != selection && !"".equals(selection.trim()))  
147                 {  
148                     where += " and " + selection;  
149                 }  
150                 return db.query("person", projection, where, selectionArgs, null, null, sortOrder);  
151             default:  
152                 throw new IllegalArgumentException("this is unkown uri:" + uri);  
153         }  
154     }  
155   
156 }  
157   
158   
159   
160 测试代码  
161 package cn.xy.test.test;  
162 import android.content.ContentResolver;  
163 import android.content.ContentValues;  
164 import android.database.Cursor;  
165 import android.net.Uri;  
166 import android.test.AndroidTestCase;  
167 import android.util.Log;  
168   
169 /** 
170  * 测试代码 
171  * @author xy 
172  * 
173  */  
174 public class TestProviders extends AndroidTestCase  
175 {  
176     // 在执行该测试方法时需要先将还有内容提供者的项目部署到Android中,否则无法找到内容提供者  
177     public void testInsert()  
178     {  
179         Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person");  
180         ContentResolver resolver = this.getContext().getContentResolver();  
181         ContentValues values = new ContentValues();  
182         values.put("name", "xy");  
183         values.put("phone", "111");  
184         resolver.insert(uri, values); // 内部调用内容提供者的insert方法  
185     }  
186   
187     // 不带id参数的删除  
188     public void testDelete1()  
189     {  
190         Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person");  
191         ContentResolver resolver = this.getContext().getContentResolver();  
192         int rowAffect = resolver.delete(uri, null, null);  
193         Log.i("rowAffect", String.valueOf(rowAffect));  
194     }  
195   
196     // 带参数的删除,通过URI传递了id至contentProvider并可追加其他条件  
197     public void testDelete2()  
198     {  
199         Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/18");  
200         ContentResolver resolver = this.getContext().getContentResolver();  
201         int rowAffect = resolver.delete(uri, "name = ?", new String[] { "XY2" }); // 在provider中手动进行了拼装  
202         Log.i("rowAffect", String.valueOf(rowAffect));  
203     }  
204       
205     public void testUpdate()  
206     {  
207         Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/19");  
208         ContentResolver resolver = this.getContext().getContentResolver();  
209         ContentValues values = new ContentValues();  
210         values.put("name", "newxy");  
211         values.put("phone", "new111");  
212         int rowAffect = resolver.update(uri, values, null, null);  
213         Log.i("rowAffect", String.valueOf(rowAffect));  
214     }  
215       
216     public void testQuery()  
217     {  
218         Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/19");  
219         ContentResolver resolver = this.getContext().getContentResolver();  
220         Cursor cursor = resolver.query(uri, new String[]{"id","name","phone"}, null, null, "id asc");  
221         if(cursor.moveToFirst())  
222         {  
223             Log.i("query", cursor.getString(cursor.getColumnIndex("name")));  
224         }  
225         cursor.close();  
226     }  
227 }  

 

你可能感兴趣的:(ContentProvider)