注:来自传智demo,在此仅做整理及将其共享出来供大家学习
ContentProvider 内容提供者
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。
虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同,如:
采用文件方式对外共享数据,需要进行文件操作读写数据;
采用SharedPreferences共享数据,需要使用SharedPreferences API读写数据。
而使用ContentProvider共享数据的好处是统一了数据访问方式。
1:schema,用来说明一个ContentProvider控制这些数据。 "content://"
2:主机名或授权(Authority),它定义了是哪个ContentProvider提供这些数据。
3:path路径,URI下的某一个Item。
4:ID, 通常定义Uri时使用”#”号占位符代替, 使用时替换成对应的数字
"content://com.itheima.provider/person/#" #表示数据id(#代表任意数字)
"content://com.itheima.provider/person/*" *来匹配任意文本
onCreate 其它应用第一次访问时被调。
insert 外部应用使用此方法添加数据。
delete 外部应用使用此方法删除数据。
update 外部应用使用此方法更新数据。
query 外部应用使用此方法查询数据。
getType 主要用于匹配数据类型(例如:接收系统广播时传递的数据类型),返回当前Uri所代表数据的MIME类型。如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/自定义类型。数据属于非集合类型数据,应该返回vnd.android.cursor.item/自定义类型。
UriMatcher 用于匹配Uri
ContentUris 获取和添加Uri信息
UriMatcher类使用介绍
UriMatcher类用于匹配Uri,它的用法如下:
首先第一步把你需要匹配Uri路径全部给注册上,如下:
//常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
UriMatcher sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//如果match()方法匹配content://cn.itcast.provider.personprovider/person路径,返回匹配码为1
sMatcher.addURI(“cn.itcast.provider.personprovider”, “person”, 1);//添加需要匹配uri,如果匹配就会返回匹配码
//如果match()方法匹配content://cn.itcast.provider.personprovider/person/230路径,返回匹配码为2
sMatcher.addURI(“cn.itcast.provider.personprovider”, “person/#”, 2);//#号为通配符
switch (sMatcher.match(Uri.parse("content://cn.itcast.provider.personprovider/person/10"))) {
case 1
break;
case 2
break;
default://不匹配
break;
}
注册完需要匹配的Uri后,就可以使用sMatcher.match(uri)方法对输入的Uri进行匹配,如果匹配就返回匹配码,匹配码是调用addURI()方法传入的第三个参数,假设匹配content://cn.itcast.provider.personprovider/person路径,返回的匹配码为1
ContentUris类使用介绍
ContentUris类用于获取Uri路径后面的ID部分,它有两个比较实用的方法:
withAppendedId(uri, id)用于为路径加上ID部分:
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person")
Uri resultUri = ContentUris.withAppendedId(uri, 10);
//生成后的Uri为:content://cn.itcast.provider.personprovider/person/10
parseId(uri)方法用于从路径中获取ID部分:
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person/10")
long personid = ContentUris.parseId(uri);//获取的结果为:10
另外Uri类中还有一个静态方法withAppendedPath(baseUri, pathSegment)也可以在某个路径上继续添加路径:
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person")
Uri resultUri = Uri.withAppendedPath(uri, “update”);
// 生成后的Uri为: content://cn.itcast.provider.personprovider/person/update
、、、
- 写一个类继承ContentProvider
- 在androidmanifest.xml文件中注册这个provider,并注册authorities属性(定义是哪个contentprovider提供数据)
- 重写增删改查方法,在UriMatcher中添加需要匹配的URI路径
4.在外部应用中通过UriMatcher中注册的uri去访问provider
、、、
用法示例:
PersonContentProvider.java 继承<span style="font-family: Arial, Helvetica, sans-serif;">ContentProvide</span>
package com.itheima28.sqlitedemo.providers; import com.itheima28.sqlitedemo.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 final String AUTHORITY = "com.itheima28.sqlitedemo.providers.PersonContentProvider"; private static final int PRESON_INSERT_CODE = 0; // 操作person表添加的操作的uri匹配码 private static final int PERSON_DELETE_CODE = 1; private static final int PERSON_UPDATE_CODE = 2; private static final int PERSON_QUERY_ALL_CODE = 3; private static final int PERSON_QUERY_ITEM_CODE = 4; private static UriMatcher uriMatcher; private PersonSQLiteOpenHelper mOpenHelper; // person表的数据库帮助对象 @Override public boolean onCreate() { mOpenHelper = new PersonSQLiteOpenHelper(getContext()); return true; } static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 添加一些uri(分机号) // content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/insert uriMatcher.addURI(AUTHORITY, "person/insert", PRESON_INSERT_CODE); // content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/delete uriMatcher.addURI(AUTHORITY, "person/delete", PERSON_DELETE_CODE); // content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/update uriMatcher.addURI(AUTHORITY, "person/update", PERSON_UPDATE_CODE); // content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/queryAll uriMatcher.addURI(AUTHORITY, "person/queryAll", PERSON_QUERY_ALL_CODE); // content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/# uriMatcher.addURI(AUTHORITY, "person/query/#", PERSON_QUERY_ITEM_CODE); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mOpenHelper.getReadableDatabase(); switch (uriMatcher.match(uri)) { case PERSON_QUERY_ALL_CODE: // 查询所有人的uri if(db.isOpen()) { Cursor cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder); return cursor; // db.close(); 返回cursor结果集时, 不可以关闭数据库 } break; case PERSON_QUERY_ITEM_CODE: // 查询的是单条数据, uri末尾出有一个id if(db.isOpen()) { long id = ContentUris.parseId(uri); Cursor cursor = db.query("person", projection, "_id = ?", new String[]{id + ""}, null, null, sortOrder); return cursor; } break; default: throw new IllegalArgumentException("uri不匹配: " + uri); } return null; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case PERSON_QUERY_ALL_CODE: // 返回多条的MIME-type return "vnd.android.cursor.dir/person"; case PERSON_QUERY_ITEM_CODE: // 返回单条的MIME-TYPE return "vnd.android.cursor.item/person"; default: break; } return null; } @Override public Uri insert(Uri uri, ContentValues values) { switch (uriMatcher.match(uri)) { case PRESON_INSERT_CODE: // 添加人到person表中 SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if(db.isOpen()) { long id = db.insert("person", null, values); db.close(); return ContentUris.withAppendedId(uri, id); } break; default: throw new IllegalArgumentException("uri不匹配: " + 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; } }
注册:
P:注册时添加了读写权限,要在访问provider的应用中添加上这两个权限
<provider android:name=".providers.PersonContentProvider" android:authorities="com.itheima28.sqlitedemo.providers.PersonContentProvider" android:readPermission="aa.bb.cc.read" android:writePermission="aa.bb.cc.write" > </provider>
另外的应用调用方法获取数据:
TextCase.java
要在AndroidManifest.xml文件中添加上
android:readPermission="aa.bb.cc.read" android:writePermission="aa.bb.cc.write" 这两个权限
package com.itheima28.othercontentprovider; 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 TextCase extends AndroidTestCase { private static final String TAG = "TextCase"; public void testInsert() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/insert"); // 内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); ContentValues values = new ContentValues(); values.put("name", "fengjie"); values.put("age", 90); uri = resolver.insert(uri, values); Log.i(TAG, "uri: " + uri); long id = ContentUris.parseId(uri); Log.i(TAG, "添加到: " + id); } public void testDelete() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/delete"); // 内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); String where = "_id = ?"; String[] selectionArgs = {"21"}; int count = resolver.delete(uri, where, selectionArgs); Log.i(TAG, "删除行: " + count); } public void testUpdate() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.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[]{"20"}); Log.i(TAG, "更新行: " + count); } public void testQueryAll() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/queryAll"); // 内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, "_id desc"); 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(); } } public void testQuerySingleItem() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/#"); // 在uri的末尾添加一个id content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/20 uri = ContentUris.withAppendedId(uri, 20); // 内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, null); if(cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(0); String name = cursor.getString(1); int age = cursor.getInt(2); cursor.close(); Log.i(TAG, "id: " + id + ", name: " + name + ", age: " + age); } } }
运行TestCase.java中的testInsert()方法后新插入的一行数据:
访问provider是用jUnit方法进行测试
附源代码下载地址:
http://download.csdn.net/detail/wang725/8852903
contentprovider_demo 包含ContentProvider提供访问数据的继承ContentProvider的程序,也有个用junit方式方式provider的应用
版权声明:本文为博主原创文章,未经博主允许不得转载。