初涉Android之ContentProvider

初涉Android之ContentProvider

 

 

一、ContentProvider的作用,可以让其它应用访问本应用的数据

第一步:定义ContentProvider如下:

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 PersonProvider extends ContentProvider {
	
	private DBOpenHelper helper = null;
	private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
	private static final int PERSONS = 1; 
	private static final int PERSON = 2;
	
	static {
		MATCHER.addURI("cn.hpu.edu.personprovider", "person", PERSONS);
		MATCHER.addURI("cn.hpu.edu.personprovider", "person/#", PERSON);
	}
	
	/**
	 * 删除数据库中相应的数据
	 */
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = helper.getWritableDatabase();
		int num = 0;
		switch(MATCHER.match(uri)) {
		case PERSONS :
			num = db.delete("person", selection, selectionArgs);
			break;
		case PERSON :
			long rowid = ContentUris.parseId(uri);
			String where = " id = " + rowid;
			if(selection != null && !"".equals(selection.trim())) {
				where += " and " + selection;
			}
			num = db.delete("person", where, selectionArgs);
			break;
		default :
			throw new IllegalArgumentException("this is An Unkown Uri : " + uri.toString());
		}
		return num;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	/**
	 * 向内容提供者里面插入数据
	 */
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = helper.getWritableDatabase();
		switch(MATCHER.match(uri)) {
		case PERSONS:
			long rowid = db.insert("person", "name", values);
			Uri insertUri = ContentUris.withAppendedId(uri, rowid);
			return insertUri;
		default: 
			throw new IllegalArgumentException("this is An Unknown Uri:" + uri.toString());
		}
	}

	/**
	 * 该方法只调用一次用于初始化环境
	 */
	public boolean onCreate() {
		helper = new DBOpenHelper(this.getContext());
		return true;
	}

	/**
	 * 按条件查询结果集并返回游标
	 */
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = helper.getReadableDatabase();
		switch(MATCHER.match(uri)) {
		case PERSONS : 
			return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
		case PERSON :
			long rawid = ContentUris.parseId(uri);
			String where = " id = " + rawid;
			if(selection != null && !"".equals(selection.trim())) {
				where += " and " + selection;
			}
			return db.query("person", projection, where, selectionArgs, null, null, sortOrder);
		default :
			throw new IllegalArgumentException("this is An Unknown Uri : " + uri.toString());
		}
	}

	/**
	 * 更新数据
	 */
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = helper.getWritableDatabase();
		int num = 0;
		switch(MATCHER.match(uri)) {
		case PERSONS :
			num = db.update("person", values, selection, selectionArgs);
			break;
		case PERSON :
			long rowid = ContentUris.parseId(uri);
			String where = " id = " + rowid;
			if(selection != null && !"".equals(selection.trim())) {
				where += " and " + selection;
			}
			num = db.update("person", values, where , selectionArgs);
			break;
		default :
			throw new IllegalArgumentException("this is An Unknown Uri : " + uri.toString());
		}
		return num;
	}

}

 

第二步:在本应用的AndroidManifest.xml里面声明Provider

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.hpu.edu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <provider android:name=".util.PersonProvider" android:authorities="cn.hpu.edu.personprovider"></provider>
        <activity
            android:name="cn.hpu.edu.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="android.test.runner"/>
    </application>

    <instrumentation 
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="cn.hpu"
        android:label="Tests for PersonService"></instrumentation>
</manifest>

 第三步:在另外一个应用里面添加如下测试:

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;

public class TestAccessContentProvider extends AndroidTestCase {
	
	private static final String TAG = "TestAccessContentProvider";
	private static final String URI = "content://cn.hpu.edu.personprovider/person";
	
	public void testInsert() throws Exception {
		Uri uri = Uri.parse(URI);
		ContentResolver resolver = this.getContext().getContentResolver();
		ContentValues values = new ContentValues();
		values.put("id", 45);
		values.put("name", "qiernsdf");
		values.put("phone", "123456789");
		resolver.insert(uri, values);
	}
	
	public void testDelete() throws Exception {
		Uri uri = Uri.parse(URI + "/10");
		ContentResolver resolver = this.getContext().getContentResolver();
		resolver.delete(uri, null, null);
		
	}
	
	public void testUpdate() throws Exception {
		Uri uri = Uri.parse(URI + "/11");
		ContentResolver resolver = this.getContext().getContentResolver();
		ContentValues values = new ContentValues();
		values.put("name" , "updateValues");
		resolver.update(uri, values, null, null);
	}
	
	public void testFind() throws Exception {
		Uri uri = Uri.parse(URI);
		ContentResolver resolver = this.getContext().getContentResolver();
		Cursor cursor = resolver.query(uri, null, null, null, " id asc");
		while(cursor.moveToNext()) {
			Log.i(TAG ,cursor.getString(cursor.getColumnIndex("name")));
		}
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值