ContentProvider案例

本文详细介绍了内容提供者(Content Provider)的概念及其在Android应用中的实现方式,包括创建数据集、匹配Uri、执行查询、插入、删除、更新操作等关键功能。同时,提供了测试类用于验证内容提供者的正确性。

PersonProvider内容提供者类


package com.kelly.sqlite;

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;

import com.kelly.sqlite.service.DBOpenHelper;

public class PersonProvider extends ContentProvider {

	// 数据集的MIME类型字符串则应该以vnd.android.cursor.dir/开头
	public static final String PERSONS_TYPE = "vnd.android.cursor.dir/person";
	// 单一数据的MIME类型字符串应该以vnd.android.cursor.item/开头
	public static final String PERSONS_ITEM_TYPE = "vnd.android.cursor.item/person";
	public static final String AUTHORITY = "com.ali.providers.personprovider";// 主机名

	public static final Uri PERSONS_URI = Uri.parse("content://" + AUTHORITY
			+ "/person");
	private DBOpenHelper dbOpenHelper = null;

	/* 自定义匹配码 */
	private static final int PERSONS_1 = 1;// 类似集合类型
	private static final int PERSONS_2 = 2;// 单条数据

	// UriMatcher类用来匹配Uri,使用match()方法匹配路径时返回匹配码
	private static final UriMatcher MATCHER;

	static {

		// 常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
		MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

		MATCHER.addURI(AUTHORITY, "person", PERSONS_1);

		MATCHER.addURI(AUTHORITY, "person/#", PERSONS_2);
	}

	@Override
	public boolean onCreate() {

		dbOpenHelper = new DBOpenHelper(getContext());

		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();

		switch (MATCHER.match(uri)) {
		case 1:// 查询所有记录 select * from person

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

		case 2:// 查询某天记录 select * from person where id =?

			long rowid = ContentUris.parseId(uri);
			String where = "personid = " + rowid;

			if (selection != null && !"".endsWith(selection.trim())) {
				where += " and " + selection;
			}
			return database.query("person", projection, where, selectionArgs,
					null, null, sortOrder);

		default:

			throw new IllegalArgumentException("this is Unknow Uri" + uri);
		}

	}

	@Override
	public String getType(Uri uri) {

		switch (MATCHER.match(uri)) {
		case 1:// 集合类型

			return PERSONS_TYPE;

		case 2:// 单挑记录
			return PERSONS_ITEM_TYPE;

		default:

			throw new IllegalArgumentException("this is Unknow Uri" + uri);
		}

	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {

		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
		switch (MATCHER.match(uri)) {
		case 1:

			long rowid = database.insert("person", "name", values);//

			Uri insertUri = ContentUris.withAppendedId(uri, rowid);

			this.getContext().getContentResolver().notifyChange(uri, null);// 发出数据变化通知
			return insertUri;

		default:

			throw new IllegalArgumentException("this is Unknow Uri" + uri);

		}
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();

		int num = 0;
		switch (MATCHER.match(uri)) {
		case 1:// 删除所有记录 delete from person

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

		case 2:// 删除某天记录 delete from person where id = ?

			long rowid = ContentUris.parseId(uri);
			String where = "personid = " + rowid;

			if (selection != null && !"".endsWith(selection.trim())) {
				where += " and " + selection;
			}
			num = database.delete("person", where, selectionArgs);
			return num;
		default:

			throw new IllegalArgumentException("this is Unknow Uri" + uri);
		}

	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {

		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();

		int num = 0;
		switch (MATCHER.match(uri)) {
		case 1:// 更新所有记录 update person ...

			num = database.update("person", values, selection, selectionArgs);
			return num;
		case 2:// 更新某天记录 update person set name = ? where id =?

			long rowid = ContentUris.parseId(uri);
			String where = "personid = " + rowid;

			if (selection != null && !"".endsWith(selection.trim())) {
				where += " and " + selection;
			}
			num = database.update("person", values, where, selectionArgs);
			return num;
		default:

			throw new IllegalArgumentException("this is Unknow Uri" + uri);
		}
	}

}

文件清单


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kelly.sqlite"
    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=".PersonProvider"
            android:authorities="com.ali.providers.personprovider"
            android:exported="true" >
        </provider>

        <activity
            android:name="com.kelly.sqlite.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="com.kelly.sqlite" >
    </instrumentation>

</manifest>

内容提供者测试类



package com.kelly.other.test;

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 AccessContentProviderTest extends AndroidTestCase {

	private static final String TAG = "AccessContentProviderTest";

	public void testInsert() throws Exception {

		String uriString = "content://com.ali.providers.personprovider/person";
		Uri uri = Uri.parse(uriString);
		ContentResolver resolver = this.getContext().getContentResolver();
		ContentValues values = new ContentValues();
		values.put("name", "shabi");
		values.put("phone", "10101010");
		values.put("amount", "101021010");
		resolver.insert(uri, values);

	}

	public void testDelete() {

		String uriString = "content://com.ali.providers.personprovider/person/11";
		Uri uri = Uri.parse(uriString);
		ContentResolver resolver = this.getContext().getContentResolver();
		resolver.delete(uri, null, null);

	}

	public void testUpdate() {

		String uriString = "content://com.ali.providers.personprovider/person/8";
		Uri uri = Uri.parse(uriString);
		ContentResolver resolver = this.getContext().getContentResolver();
		ContentValues values = new ContentValues();
		values.put("name", "yueyuan");
		values.put("phone", "110");
		resolver.update(uri, values, null, null);

	}

	public void testQuery() {

		String uriString = "content://com.ali.providers.personprovider/person";
		Uri uri = Uri.parse(uriString);
		ContentResolver resolver = this.getContext().getContentResolver();
		Cursor cursor = resolver.query(uri, null, null, null, "personid asc");
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("name"));
			Log.i(TAG, name);
		}
		cursor.close();

	}
}

代码下载地址:http://download.youkuaiyun.com/detail/leokelly001/8123947

包括contentprovider共享数据及监听数据变化


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值