android 四大重要的组件之ContentProvider

Android开发中四个重要的组件:

1、Activiyt

2、Broadcast Intent Receiver

3、Service

4、Content Provider

一个ContentProvider类实现了一组标准的方法接口,从而能够让其他的应用保存或读取此ContentProvider的各种数据类型。

下面列举一些常用的接口:

1、query(Uri uri,String[] projection,String selection,String[]selectionArgs,String sortOrder):通过Uri进行查询,返回一个Cursor.

2、insert(Uri uri,ContentValues values):将一组数据插入到Uri指定的地方。

3、update(Uri uri,ContentValues values,String where,String[]selectionArgs):更新Uri指定位置的数据。

4、delete(Uriuri,String where,String[] selectionArgs):删除指定Uri并且符合一定条件的数据。

ContentResolver

外界程序通过ContentResolver接口可以访问ContentProvider提供的数据,在Activity当中通过getContentResolver()可以得到当前应用ContentResolver实例。其提供的接口与ContentProvider提供的接口对应:

1、query(Uri uri,String[] projection,String selection,String[]selectionArgs,String sortOrder):通过Uri进行查询,返回一个Cursor.

2、insert(Uri uri,ContentValues values):将一组数据插入到Uri指定的地方。

3、update(Uri uri,ContentValues values,String where,String[]selectionArgs):更新Uri指定位置的数据。

4、delete(Uriuri,String where,String[] selectionArgs):删除指定Uri并且符合一定条件的数据。

实例:

1.要为当前应用程序的私有数据定义URI,就需要专门定义个继承自ContentProvider的类,然后实现各个不同的操作所调用的方法。

1、PersonProvider

package cn.class3g.db;

 

import cn.class3g.service.DatabaseHelper;

importandroid.content.ContentProvider;

import android.content.ContentUris;

importandroid.content.ContentValues;

importandroid.content.UriMatcher;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

import android.net.Uri;

 

public class PersonProvider extendsContentProvider {

       privatestatic UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

 

       privatestatic final int PERSONS = 1;

       privatestatic final int PERSON = 2;

 

       privateDatabaseHelper dbHelper;

 

       static{

              matcher.addURI("cn.class3g.providers.personprovider", "person",PERSONS);

              matcher.addURI("cn.class3g.providers.personprovider","person/#",

                            PERSON);

       }

 

       publicboolean onCreate() {

              dbHelper= new DatabaseHelper(this.getContext());

              returntrue;

       }

 

       // content://cn.itcast.provides.personprovider/person

       public Uri insert(Uri uri, ContentValuesvalues) {

              SQLiteDatabasedb = dbHelper.getWritableDatabase();

              longrowId;

 

              switch(matcher.match(uri)) {

              casePERSONS: //向表中添加新纪录并返回其行号

                     rowId= db.insert("person", "personid", values);

                     returnContentUris.withAppendedId(uri, rowId);

              default:

                     thrownew IllegalArgumentException("Unknow Uri:" + uri);

              }

       }

 

       publicCursor query(Uri uri, String[] projection, String selection,

                     String[]selectionArgs, String sortOrder) {

              SQLiteDatabasedb = dbHelper.getReadableDatabase();

              switch(matcher.match(uri)) {

              casePERSONS:

                     returndb.query("person", projection, selection, selectionArgs, null, null,sortOrder);

              casePERSON:

                     longpersonid = ContentUris.parseId(uri);

                     Stringwhere = "personid="+ personid;

                     if(selection!=null&& !"".equals(selection)){

                            where= where + " and "+ selection;

                     }

                     returndb.query("person", projection, where, selectionArgs, null, null,sortOrder);

                    

              default:

                     thrownew IllegalArgumentException("Unknown Uri:"+ uri);

              }

       }

 

       // content://cn.itcast.provides.personprovider/person 更新表中的所有记录

       // content://cn.itcast.provides.personprovider/person/10 更新表中指定id的记录

       publicint update(Uri uri, ContentValues values, String selection,

                     String[]selectionArgs) {

              SQLiteDatabasedb = dbHelper.getWritableDatabase();

              intnum;

              switch(matcher.match(uri)){

              casePERSONS: //更新指定记录

                     num= db.update("person", values, selection, selectionArgs);

                     break;

              casePERSON:

                     longpersonid = ContentUris.parseId(uri);

                     Stringwhere = "personid=" + personid;

                     if(selection!= null){

                            where+= " and " + selection;

                     }

                     num= db.update("person", values, where, selectionArgs);

                     break;

              default:

                     thrownew IllegalArgumentException("Unknow Uri"+uri);

              }

              returnnum;

       }

 

       publicint delete(Uri uri, String selection, String[] selectionArgs) {

              SQLiteDatabasedb = dbHelper.getWritableDatabase();

              intnum = 0;

              switch(matcher.match(uri)) {

              casePERSONS:

                     num= db.delete("person", selection, selectionArgs);

                     break;

              casePERSON:

                     longpersonid = ContentUris.parseId(uri);

                     Stringwhere = "personid="+ personid;

                     if(selection!=null&& !"".equals(selection)){

                            where= where + " and "+ selection;

                     }

                     num= db.delete("person", where, selectionArgs);

                     break;    

              default:

                     thrownew IllegalArgumentException("Unknown Uri:"+ uri);

              }

              returnnum;

       }

 

       publicString getType(Uri uri) {

              switch(matcher.match(uri)) {

              casePERSONS:

                     return"vnd.android.cursor.dir/person";

              casePERSON:

                     return"vnd.android.cursor.item/person";

              default:

                     thrownew IllegalArgumentException("Unknown Uri:"+ uri);

              }

       }

}

2.在AndroidManifest中配置

 <provider

           android:authorities="cn.class3g.providers.personprovider"

           android:name="PersonProvider" >

       </provider>

3.建立测试工程编写测试代码

 

public class AccessContentProviderTestextends AndroidTestCase {

      

       publicvoid testSave() throws Throwable{

              ContentResolverresolver = this.getContext().getContentResolver();

              UriinsertUri = Uri.parse("content://cn.class3g.providers.personprovider/person");

              ContentValuesvalues = new ContentValues();

              values.put("name","laozhang");

              values.put("age","50");

              Uriuri = resolver.insert(insertUri, values);

              Log.i("TAG",uri.toString());

       }

      

       publicvoid testQuery() throws Throwable{

              ContentResolverresolver = this.getContext().getContentResolver();

              Uriuri = Uri.parse("content://cn.class3g.providers.personprovider/person");

             

              Cursorcursor = resolver.query(uri, null, null, null, "personid asc");

             

              while(cursor.moveToNext()){

                     intpersonid = cursor.getInt(cursor.getColumnIndex("personid"));

                     Stringname = cursor.getString(cursor.getColumnIndex("name"));

                    

                     Log.i("TAG","personid="+ personid + ",name="+ name);

              }

              cursor.close();

       }

      

       publicvoid testUpdate() throws Throwable{

              ContentResolvercontentResolver =

this.getContext().getContentResolver();

              UriupdateUri = Uri.parse("content://cn.class3g.providers.personprovider/person/5");

              ContentValuesvalues = new ContentValues();

              values.put("name","袁世凯");

              contentResolver.update(updateUri,values, null, null);

       }

       publicvoid testDelete() throws Throwable{

              ContentResolvercontentResolver = this.getContext().getContentResolver();

              Uriuri = Uri.parse("content://cn.class3g.providers.personprovider/person/5");

              contentResolver.delete(uri,null, null);

       }    

}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值