Android自定义ContentProvider

http://www.cnblogs.com/EggKiller/p/3410465.html

http://byandby.iteye.com/blog/837466

1、MLDNDatabaseMetaData.java

确定contentprovider的AUTHORITY、以及新增的MIME数据类型

package org.lxh.demo;

import android.net.Uri;
import android.provider.BaseColumns;

public interface MLDNDatabaseMetaData {
	// 这个是外部访问的Authority,Content地址为:content//org.lxh.demo.membercontentprovider
	public static final String AUTHORITY = "org.lxh.demo.membercontentprovider" ;
	// 数据库的名字
	public static final String DATABASE_NAME = "mldn" ;	// 操作的数据库的名字
	public static final int VERSION = 1 ;	// 数据库的版本
	
	public static interface MemberTableMetaData extends BaseColumns{
		public static final String TABLE_NAME = "member" ;	// 表名称
		// 外部程序访问本表的Uri地址,而且名称都统一设置为CONTENT_URI
		public static final Uri CONTENT_URI = Uri.parse("content://"
				+ AUTHORITY + "/" + TABLE_NAME);
		// 得到member表中的全部记录
		public static final String CONTACT_LIST = "vnd.android.cursor.dir/vnd.mldncontentprovider.member" ;
		// 取得一个member的信息,相当于就是按照ID查询
		public static final String CONTACT_ITEM = "vnd.android.cursor.item/vnd.mldncontentprovider.member" ;
		
		public static final String MEMBER_NAME = "name" ;
		public static final String MEMBER_AGE = "age" ;
		public static final String MEMBER_BIRTHDAY = "birthday" ;
		
		public static final String SORT_ORDER = "_id DESC" ;// 排序操作
	}
}
2、MyDatabaseHelper.java

 创建存储数据用的表,

package org.lxh.demo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {
	public MyDatabaseHelper(Context context) {
		super(context, MLDNDatabaseMetaData.DATABASE_NAME, null,
				MLDNDatabaseMetaData.VERSION);
	}<pre name="code" class="java">package org.lxh.demo;

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 MemberContentProvider extends ContentProvider {
	private static UriMatcher uriMatcher = null ;	// 地址转换
	private static final int GET_MEMBER_LIST = 1 ;	// 得到全部的数据
	private static final int GET_MEMBER_ITEM = 2 ;	// 取得一个数据
	private MyDatabaseHelper helper = null ;
	static {	// 静态代码块
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH) ;	// 实例化对象
		uriMatcher.addURI(MLDNDatabaseMetaData.AUTHORITY,
				MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
				GET_MEMBER_LIST);	// 取得全部数据的匹配地址
		uriMatcher.addURI(MLDNDatabaseMetaData.AUTHORITY,
				MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME + "/#",
				GET_MEMBER_ITEM);	// 取得一个数据的匹配地址
	}

	@Override
	public String getType(Uri uri) { // 取得数据的类型的
		switch (uriMatcher.match(uri)) { // 匹配传入进来的Uri的类型
		case GET_MEMBER_LIST:
			return MLDNDatabaseMetaData.MemberTableMetaData.CONTACT_LIST;
		case GET_MEMBER_ITEM:
			return MLDNDatabaseMetaData.MemberTableMetaData.CONTACT_ITEM;
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
	}

	@Override
	public boolean onCreate() {
		this.helper = new MyDatabaseHelper(super.getContext()) ;
		return true;	// 操作成功了
	}
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs)  {
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		int result = 0	;	// 操作结果
		switch (uriMatcher.match(uri)) {
		case GET_MEMBER_LIST:
			result = db.delete(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					selection, selectionArgs);	// 删除全部
			break ;
		case GET_MEMBER_ITEM:
			long id = ContentUris.parseId(uri) ;	// 找到一个数据的ID
			String where = "_id=" + id ;
			result = db.delete(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME, where,
					selectionArgs);
			break ;
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
		return result;
	}



	@Override
	public Uri insert(Uri uri, ContentValues values) {	// content://org.lxh.demo.membercontentprovider/member
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		long id = 0 ;	// 取得增长后的数据ID
		switch(uriMatcher.match(uri)) {
		case GET_MEMBER_LIST :
			id = db.insert(MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					MLDNDatabaseMetaData.MemberTableMetaData._ID, values);
			String uriPath = uri.toString() ;
			String path = uriPath + "/" + id ;
			return Uri.parse(path) ;
		case GET_MEMBER_ITEM :
			return null ; 
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
	}



	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		switch (uriMatcher.match(uri)) {
		case GET_MEMBER_LIST:
			return db
					.query(MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
							projection, selection, selectionArgs, null, null,
							sortOrder);
		case GET_MEMBER_ITEM:
			long id = ContentUris.parseId(uri) ;	// 找到ID
			String where = "_id=" + id ;
			return db
					.query(MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
							projection, where, selectionArgs, null, null,
							sortOrder);
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		int result = 0 ;	// 表示结果
		switch (uriMatcher.match(uri)) {
		case GET_MEMBER_LIST:
			result = db.update(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					values, null, null);
			break ;
		case GET_MEMBER_ITEM:
			long id = ContentUris.parseId(uri) ;	// 找到里面的id
			String where = "_id=" + id ;
			result = db.update(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					values, where, selectionArgs);
			break ;
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
		return result ; 
	}

}


3、MemberContentProvider.java

继承ContentProvider、并实现增删改查方法

package org.lxh.demo;

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 MemberContentProvider extends ContentProvider {
	private static UriMatcher uriMatcher = null ;	// 地址转换
	private static final int GET_MEMBER_LIST = 1 ;	// 得到全部的数据
	private static final int GET_MEMBER_ITEM = 2 ;	// 取得一个数据
	private MyDatabaseHelper helper = null ;
	static {	// 静态代码块
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH) ;	// 实例化对象
		uriMatcher.addURI(MLDNDatabaseMetaData.AUTHORITY,
				MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
				GET_MEMBER_LIST);	// 取得全部数据的匹配地址
		uriMatcher.addURI(MLDNDatabaseMetaData.AUTHORITY,
				MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME + "/#",
				GET_MEMBER_ITEM);	// 取得一个数据的匹配地址
	}

	@Override
	public String getType(Uri uri) { // 取得数据的类型的
		switch (uriMatcher.match(uri)) { // 匹配传入进来的Uri的类型
		case GET_MEMBER_LIST:
			return MLDNDatabaseMetaData.MemberTableMetaData.CONTACT_LIST;
		case GET_MEMBER_ITEM:
			return MLDNDatabaseMetaData.MemberTableMetaData.CONTACT_ITEM;
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
	}

	@Override
	public boolean onCreate() {
		this.helper = new MyDatabaseHelper(super.getContext()) ;
		return true;	// 操作成功了
	}
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs)  {
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		int result = 0	;	// 操作结果
		switch (uriMatcher.match(uri)) {
		case GET_MEMBER_LIST:
			result = db.delete(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					selection, selectionArgs);	// 删除全部
			break ;
		case GET_MEMBER_ITEM:
			long id = ContentUris.parseId(uri) ;	// 找到一个数据的ID
			String where = "_id=" + id ;
			result = db.delete(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME, where,
					selectionArgs);
			break ;
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
		return result;
	}



	@Override
	public Uri insert(Uri uri, ContentValues values) {	// content://org.lxh.demo.membercontentprovider/member
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		long id = 0 ;	// 取得增长后的数据ID
		switch(uriMatcher.match(uri)) {
		case GET_MEMBER_LIST :
			id = db.insert(MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					MLDNDatabaseMetaData.MemberTableMetaData._ID, values);
			String uriPath = uri.toString() ;
			String path = uriPath + "/" + id ;
			return Uri.parse(path) ;
		case GET_MEMBER_ITEM :
			return null ; 
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
	}



	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		switch (uriMatcher.match(uri)) {
		case GET_MEMBER_LIST:
			return db
					.query(MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
							projection, selection, selectionArgs, null, null,
							sortOrder);
		case GET_MEMBER_ITEM:
			long id = ContentUris.parseId(uri) ;	// 找到ID
			String where = "_id=" + id ;
			return db
					.query(MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
							projection, where, selectionArgs, null, null,
							sortOrder);
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = this.helper.getWritableDatabase() ;// 以写方式打开数据库
		int result = 0 ;	// 表示结果
		switch (uriMatcher.match(uri)) {
		case GET_MEMBER_LIST:
			result = db.update(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					values, null, null);
			break ;
		case GET_MEMBER_ITEM:
			long id = ContentUris.parseId(uri) ;	// 找到里面的id
			String where = "_id=" + id ;
			result = db.update(
					MLDNDatabaseMetaData.MemberTableMetaData.TABLE_NAME,
					values, where, selectionArgs);
			break ;
		default:
			throw new UnsupportedOperationException("Not Support Operation :"
					+ uri);
		}
		return result ; 
	}

}

4、MyContentProviderDemo.java

测试

package org.lxh.demo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MyContentProviderDemo extends Activity {
	private Button insertBut = null ;	// 操作按钮
	private Button updateBut = null ;
	private Button deleteBut = null ;
	private Button queryBut = null ;
	private TextView mainInfo = null ;
	private ListView memberList = null ;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.main);
		this.mainInfo = (TextView) super.findViewById(R.id.mainInfo) ;	// 取得组件
		this.insertBut = (Button) super.findViewById(R.id.insertBut) ;	// 取得组件
		this.updateBut = (Button) super.findViewById(R.id.updateBut) ;	// 取得组件
		this.deleteBut = (Button) super.findViewById(R.id.deleteBut) ;	// 取得组件
		this.queryBut = (Button) super.findViewById(R.id.queryBut) ;	// 取得组件
		this.memberList = (ListView) super.findViewById(R.id.memberList) ;	// 取得组件
		this.insertBut.setOnClickListener(new InsertOnClickListener()) ;
		this.updateBut.setOnClickListener(new UpdateOnClickListener()) ;
		this.deleteBut.setOnClickListener(new DeleteOnClickListener()) ;
		this.queryBut.setOnClickListener(new QueryOnClickListener()) ;
	}
	private class InsertOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			MyContentProviderDemo.this.mainInfo.setText("执行的是增加操作...") ;
			long id = 0 ;	// 接收返回的id数据
			id = MyContentProviderDemo.this.testInsert("李兴华", 30,
					new SimpleDateFormat("yyyy-MM-dd").format(new Date()));	// 增加数据
			Toast.makeText(MyContentProviderDemo.this, "数据增加成功,ID为:" + id,
					Toast.LENGTH_LONG).show();
		}
		
	}
	private class DeleteOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			MyContentProviderDemo.this.mainInfo.setText("执行的是删除操作...") ;
			long result = 0 ;	// 接收返回的id数据
			result = MyContentProviderDemo.this.testDelete(String.valueOf(4)); // 更新数据
			Toast.makeText(MyContentProviderDemo.this, "删除了" + result + "条记录",
					Toast.LENGTH_LONG).show();
		}
		
	}
	private class QueryOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			MyContentProviderDemo.this.mainInfo.setText("执行的是查询操作...") ;
			Cursor result = MyContentProviderDemo.this.testQuery(null) ;	// 查询全部
			MyContentProviderDemo.this.startManagingCursor(result) ;	// 结果集交给系统管理
			List<Map<String,Object>> members = new ArrayList<Map<String,Object>>() ;
			for (result.moveToFirst(); !result.isAfterLast(); result
					.moveToNext()) {
				Map<String,Object> member = new HashMap<String,Object>() ;
				member.put("_id", result.getInt(0)) ;
				member.put("name", result.getString(1)) ;
				member.put("age", result.getInt(2)) ;
				member.put("birthday", result.getString(3)) ;
				members.add(member) ;
			}
			MyContentProviderDemo.this.memberList
					.setAdapter(new SimpleAdapter(MyContentProviderDemo.this,
							members, R.layout.member, new String[] { "_id",
									"name", "age", "birthday" }, new int[] {
									R.id._id, R.id.name, R.id.age,
									R.id.birthday }));
			Toast.makeText(MyContentProviderDemo.this, "数据查询成功!",
					Toast.LENGTH_LONG).show();
		}
		
	}
	private class UpdateOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			MyContentProviderDemo.this.mainInfo.setText("执行的是更新操作...") ;
			long result = 0 ;	// 接收返回的id数据
			result = MyContentProviderDemo.this.testUpdate("", "MLDN", 18,
					"1989-09-19"); // 更新数据
			Toast.makeText(MyContentProviderDemo.this, "更新了" + result + "条记录",
					Toast.LENGTH_LONG).show();
		}
		
	}
	private long testInsert(String name,int age,String birthday) {	// 执行增加操作
		ContentResolver contentResolver = super.getContentResolver() ;	// 取得ContentResolver对象
		ContentValues values = new ContentValues() ;
		values.put(MLDNDatabaseMetaData.MemberTableMetaData.MEMBER_NAME, name) ;
		values.put(MLDNDatabaseMetaData.MemberTableMetaData.MEMBER_AGE, age) ;
		values.put(MLDNDatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY, birthday) ;
		Uri resultUri = contentResolver.insert(
				MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI, values);
		return ContentUris.parseId(resultUri) ;	// 解析出返回的id数据
	}

	private long testUpdate(String _id, String name, int age, String birthday) { // 执行增加操作
		long result = 0 ;	// 返回结果
		ContentResolver contentResolver = super.getContentResolver() ;	// 取得ContentResolver对象
		ContentValues values = new ContentValues() ;
		values.put(MLDNDatabaseMetaData.MemberTableMetaData.MEMBER_NAME, name) ;
		values.put(MLDNDatabaseMetaData.MemberTableMetaData.MEMBER_AGE, age) ;
		values.put(MLDNDatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY, birthday) ;
		
		if(_id == null || "".equals(_id)) {	// 更新全部
			result = contentResolver.update(MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI, values, null, null) ;
		} else {	// 按照id更新
			result = contentResolver.update(
					Uri.withAppendedPath(MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI, _id),
					values, null, null);
		}
		return result ;	// 解析出返回的id数据
	}
	
	private long testDelete(String _id) {
		ContentResolver contentResolver = super.getContentResolver() ;	// 取得ContentResolver对象
		long result = 0 ;
		if (_id == null || "".equals(_id)) {
			result = contentResolver.delete(
					MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI, null,
					null);
		} else {
			result = contentResolver.delete(Uri.withAppendedPath(
					MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI, _id),
					null, null);
		}
		return result ;
	}
	
	private Cursor testQuery(String id) {
		if(id == null || "".equals(id)) {	// 查询全部
			return super.getContentResolver().query(
					MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI, null,
					null, null,
					MLDNDatabaseMetaData.MemberTableMetaData.SORT_ORDER);
		} else {
			return super
					.getContentResolver()
					.query(Uri.withAppendedPath(
							MLDNDatabaseMetaData.MemberTableMetaData.CONTENT_URI,
							id), null, null, null,
							MLDNDatabaseMetaData.MemberTableMetaData.SORT_ORDER);
		}
	}
}

5、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="org.lxh.demo" android:versionCode="1" android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<provider
			android:name=".MemberContentProvider"
			android:authorities="org.lxh.demo.membercontentprovider" />
		<activity android:name=".MyContentProviderDemo"
			android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

	</application>
</manifest>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值