Android中內容提供者ContentProvider實現數據庫增刪改查

1.我們首先new一個我們自己的類集成ContentProvider,並實現方法如下

package com.wzw.sqllitedemo.providers;

import com.wzw.sqllitedemo.db.PersonSQLiteOpenHelper;

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 uriMatcher;
	private static final String authority="com.wzw.sqllitedemo.providers.PersonContentProvider";
	private static final int PERSON_INSERT_CODE = 0;
	private static final int PERSON_DELETE_CODE = 1;
	private static final int PERSON_UPDATE_CODE = 2;
	private static final int PERSON_QUERYALL_CODE = 3;
	private PersonSQLiteOpenHelper mOpenHelper;
	static{
		uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
		//添加uri(分機號)
		//content://com.wzw.sqllitedemo.providers.PersonContentProvider/person/insert
		uriMatcher.addURI(authority, "person/insert", PERSON_INSERT_CODE);
		
		uriMatcher.addURI(authority, "person/delete", PERSON_DELETE_CODE);
		
		uriMatcher.addURI(authority, "person/update", PERSON_UPDATE_CODE);
		
		uriMatcher.addURI(authority, "person/queryAll", PERSON_QUERYALL_CODE);
		
	}
	@Override
	public boolean onCreate() {
		mOpenHelper=new PersonSQLiteOpenHelper(getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		switch (uriMatcher.match(uri)) {
		case PERSON_QUERYALL_CODE:
			
			SQLiteDatabase db=mOpenHelper.getReadableDatabase();
			if(db.isOpen()){
				
				Cursor cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
				return cursor;
			//	db.close();返回cursor結果集時不能關閉數據庫
			}
			break;

		default:
			throw new IllegalArgumentException("uri不匹配");
		}
		return null;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

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

		switch (uriMatcher.match(uri)) {
		case PERSON_INSERT_CODE:		//添加人到person表中
			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			if (db.isOpen()) {
				long id = db.insert("person", null, values);
				
				db.close();
				//返回的類型爲content://com.wzw.sqllitedemo.providers.PersonContentProvider/person/insert/id
				return ContentUris.withAppendedId(uri, id);
			}
			break;

		default:
			throw new IllegalArgumentException("uri不匹配");
		}
		return null;
	}

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

		switch (uriMatcher.match(uri)) {
		case PERSON_DELETE_CODE:	//在person中刪除數據
			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			if(db.isOpen()){
				int count=db.delete("person", selection, selectionArgs);
				
				db.close();
				return count;
			}
			break;
		default:
			throw new IllegalArgumentException("uri不匹配"+uri);
		}
		return 0;
	}

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

		switch (uriMatcher.match(uri)) {
		case PERSON_UPDATE_CODE:		//更新person表
			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			if(db.isOpen()){
				int count=db.update("person", values, selection, selectionArgs);
				
				db.close();
				return count;
			}
			break;

		default:
			throw new IllegalArgumentException("uri不匹配"+uri);
		}
		return 0;
	}

}

在清單文件中聲明

        <!-- 清單文件中聲明ContextProvider -->
        <provider 
            android:name="com.wzw.sqllitedemo.providers.PersonContentProvider"
            android:authorities="com.wzw.sqllitedemo.providers.PersonContentProvider">
            
        </provider>

2.然後我們在新建一個工程來測試

新建一個junit測試類


package com.wzw.other;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import android.test.AndroidTestCase;
import android.util.Log;

public class TestCase extends AndroidTestCase {
	
	private String tag="TestCase";

	public void testInsert(){
		
		//另外一個程序的uri
		Uri uri = Uri.parse("content://com.wzw.sqllitedemo.providers.PersonContentProvider/person/insert");
		//獲取內容提供者訪問對象
		ContentResolver resolver = getContext().getContentResolver();
		ContentValues values = new ContentValues();
		values.put("name","meimei");
		values.put("age", 18);
		Log.i(tag, "uri"+uri);
		uri = resolver.insert(uri, values);
		long id = ContentUris.parseId(uri);
		Log.i(tag, "插入的id"+id);
	}
	
	public void testDelete(){
		
		//另外一個程序的uri
		Uri uri = Uri.parse("content://com.wzw.sqllitedemo.providers.PersonContentProvider/person/delete");
		//獲取內容提供者訪問對象
		ContentResolver resolver = getContext().getContentResolver();
		String where = "_id=?";
		String[] selectionArgs={"8"};
		int count = resolver.delete(uri, where, selectionArgs);
		Log.i(tag, "刪除了"+count);
	}
	
	public void tesUpdate(){
		
		//另外一個程序的uri
		Uri uri = Uri.parse("content://com.wzw.sqllitedemo.providers.PersonContentProvider/person/update");
		//獲取內容提供者訪問對象
		ContentResolver resolver = getContext().getContentResolver();
		ContentValues values=new ContentValues();
		values.put("name", "lisi");
		int count = resolver.update(uri, values, "_id=?", new String[]{"9"});
		Log.i(tag, "更新了:"+count);
	}

	public void testQueryAll(){

		//另外一個程序的uri
		Uri uri = Uri.parse("content://com.wzw.sqllitedemo.providers.PersonContentProvider/person/queryAll");
		//獲取內容提供者訪問對象
		ContentResolver resolver = getContext().getContentResolver();
		Cursor cursor = resolver.query(uri, new String[]{"_id","name","age"}, null, null, "_id");
		if(cursor!=null&&cursor.getCount()>0){
			int id;
			String name;
			int age;
			while(cursor.moveToNext()){
				id=cursor.getInt(0);
				name=cursor.getString(1);
				age=cursor.getInt(2);
				Log.i(tag, "id:"+id+"name:"+name+"age:"+age);
			}
			cursor.close();
		}
	}
}

把第一個工程部署以後。內容提供者就在手機中存在了,然後用第二個工程來測試他。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章