当前位置:首页 > 开发 > 移动开发 > 正文

初涉Android之ContentProvider

发表于: 2013-12-23   作者:chinrui   来源:转载   浏览次数:
摘要: 初涉Android之ContentProvider     一、ContentProvider的作用,可以让其它应用访问本应用的数据 第一步:定义ContentProvider如下: import android.content.ContentProvider; import android.content.ContentUris; import android.

初涉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")));
		}
	}
}

 

 

初涉Android之ContentProvider

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
星期二晚上回到寝室开始在eclipse上弄android开发,android对我来说是个新鲜的玩意,虽然玩手机游戏
鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全。 Android对
看到csdn博客上面其它大牛的系列性android博客,小弟确实十分羡慕。所以经过一番思想斗争后,小弟终
今天由于后期的需求研究了一下在Android Studio下面的NDK开发流程,以前使用Eclipse的时候也搭建过
SimpleAdapter无法自动适配BitMap 需求需要将一组图片和文字介绍通过GridView排列,我选择了SimpleAd
黑白棋,又称翻转棋,还有个说法叫奥赛罗棋,具体得名我并未去考 证。下棋方式很简单,是在游戏中通
Matlab——GUI初涉 MATLAB GUI教学视频0:GUI中的基本操作—在线播放—优酷网,视频高清在线观看 ht
云计算,是近年频繁在网络上出现的新词儿。每次看到的时候,总觉得就是一种特高级的技术,而没有深
刚开始接触linux内核,首先将linux内核进行编译,遇到一些问题,最后虽然解决了,但是还不是完全清
哎!清明节,真不好过,呆在寝室,可以说处于无奈,三天的假,下了两天的大雨,这叫人怎么不难受!
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号