使用ContentProvider共享数据

当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。以前我们学习过文件的操作模式,通过指定文件的操作模式为Context.MODE_WORLD_READABLE 或Context.MODE_WORLD_WRITEABLE同样可以对外共享数据,但数据的访问方式会因数据存储的方式而不同,如:采用xml文件对外共享数据,需要进行xml解析来读写数据;采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据。而使用ContentProvider共享数据的好处是统一了数据访问方式。

当应用需要通过ContentProvider对外共享数据时,第一步需要继承ContentProvider并重写下面方法:

publicclass PersonContentProviderextends ContentProvider{
   public booleanonCreate()
   public Uri insert(Uri uri,ContentValuesvalues)
   public intdelete(Uri uri,String selection, String[] selectionArgs)
   public intupdate(Uri uri,ContentValuesvalues, String selection, String[] selectionArgs)
   public Cursor query(Uri uri,String[] projection, String selection, String[] selectionArgs,String sortOrder)
   public String getType(Uriuri)}

第二步需要在AndroidManifest.xml使用<provider>对该ContentProvider进行配置,为了能让其他应用找到该ContentProvider , ContentProvider 采用了authorities(主机名/域名)对它进行唯一标识,你可以把 ContentProvider看作是一个网站(想想,网站也是提供数据者),authorities 就是他的域名:

<manifest .... >
   <application android:icon="@drawable/icon"android:label="@string/app_name">
        <providerandroid:name=".PersonContentProvider"android:authorities="cn.cloud.providers.personprovider"/>
   </application>
</manifest>


注意:一旦应用继承了ContentProvider类,后面我们就会把这个应用称为ContentProvider(内容提供者)。


package cn.cloud.db;

import cn.cloud.service.DBOpenHelper;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class PersonContentProvider extends ContentProvider {
	private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
	private static final int PERSONS = 1;
	private static final int PERSON = 2;
	private DBOpenHelper dbOpenHelper;
	static{
		matcher.addURI("cn.cloud.providers.personprovider", "person", PERSONS);
		matcher.addURI("cn.cloud.providers.personprovider", "person/#", PERSON);
	}

	@Override
	public boolean onCreate() {
		dbOpenHelper = new DBOpenHelper(this.getContext());
		return true;
	}
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		int num = 0 ;//已经删除的记录数量
		switch (matcher.match(uri)) {
		case PERSONS:
			num = db.delete("person", selection, selectionArgs);
			break;			
		case PERSON:
			long id = ContentUris.parseId(uri);
			String where = "personid="+ id;
			if(selection!=null && !"".equals(selection)){ // personid=12 and name=?
				where = where + " and "+ selection;
			}
			num = db.delete("person", where, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unkown Uri:"+ uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return num;
	}

	@Override
	public String getType(Uri uri) {//返回当前操作的数据类型
		switch (matcher.match(uri)) {
		case PERSONS://操作的是集合类型数据
			return "vnd.android.cursor.dir/person";
		case PERSON:
			return "vnd.android.cursor.item/person";
		default:
			throw new IllegalArgumentException("Unkown Uri:"+ uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		long id = 0 ;
		switch (matcher.match(uri)) {
		case PERSONS:
			id = db.insert("person", "personid", values);//得到记录的id
			getContext().getContentResolver().notifyChange(uri, null);
			return ContentUris.withAppendedId(uri, id);//返回代表新增记录的Uri
		case PERSON:
			id = db.insert("person", "personid", values);//得到记录的id
			String strUri = uri.toString();
			Uri personUri = Uri.parse(strUri.substring(0, strUri.lastIndexOf("/")));
			getContext().getContentResolver().notifyChange(personUri, null);
			return ContentUris.withAppendedId(personUri, id);
		default:
			throw new IllegalArgumentException("Unkown Uri:"+ uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		switch (matcher.match(uri)) {
		case PERSONS:
			return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
			
		case PERSON:
			long id = ContentUris.parseId(uri);
			String where = "personid="+ id;
			if(selection!=null && !"".equals(selection)){ // personid=12 and name=?
				where = where + " and "+ selection;
			}
			return db.query("person", projection, where, selectionArgs, null, null, sortOrder);
			
		default:
			throw new IllegalArgumentException("Unkown Uri:"+ uri);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		int num = 0 ;//已经修改的记录数量
		switch (matcher.match(uri)) {
		case PERSONS:
			num = db.update("person", values, selection, selectionArgs);
			break;			
		case PERSON:
			long id = ContentUris.parseId(uri);
			String where = "personid="+ id;
			if(selection!=null && !"".equals(selection)){ 
				where = where + " and "+ selection;
			}
			num = db.update("person", values, where, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unkown Uri:"+ uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);//通知数据发生变化
		return num;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值