contentprovider的学习实例总结
工作中遇到了contentprovider数据共享机制,下面来总结一下:
一、ContentProvider简介
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同,如:采用文件方式对外共享数据,需要进行文件操作读写数据;采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据。而使用ContentProvider共享数据的好处是统一了数据访问方式。
二、Uri类简介
Uri代表了要操作的数据,Uri主要包含了两部分信息:1.需要操作的ContentProvider ,2.对ContentProvider中的什么数据进行操作,一个Uri由以下几部分组成:
1.scheme:ContentProvider(内容提供者)的scheme已经由Android所规定为:content://。
2.主机名(或Authority):用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。
3.路径(path):可以用来表示我们要操作的数据,路径的构建应根据业务而定,如下:
• 要操作contact表中id为10的记录,可以构建这样的路径:/contact/10
• 要操作contact表中id为10的记录的name字段, contact/10/name
• 要操作contact表中的所有记录,可以构建这样的路径:/contact
要操作的数据不一定来自数据库,也可以是文件等他存储方式,如下:
要操作xml文件中contact节点下的name节点,可以构建这样的路径:/contact/name
如果要把一个字符串转换成Uri,可以使用Uri类中的parse()方法,如下:
Uri uri = Uri.parse("content://com.changcheng.provider.contactprovider/contact")
三、UriMatcher、ContentUrist和ContentResolver简介
因为Uri代表了要操作的数据,所以我们很经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris 。掌握它们的使用,会便于我们的开发工作。
UriMatcher:用于匹配Uri,它的用法如下:
1.首先把你需要匹配Uri路径全部给注册上,如下:
//常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码(-1)。
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//如果match()方法匹配content://com.changcheng.sqlite.provider.contactprovider/contact路径,返回匹配码为1
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact”, 1);//添加需要匹配uri,如果匹配就会返回匹配码
//如果match()方法匹配 content://com.changcheng.sqlite.provider.contactprovider/contact/230路径,返回匹配码为2
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact/#”, 2);//#号为通配符
2.注册完需要匹配的Uri后,就可以使用uriMatcher.match(uri)方法对输入的Uri进行匹配,如果匹配就返回匹配码,匹配码是调用addURI()方法传入的第三个参数,假设匹配content://com.changcheng.sqlite.provider.contactprovider/contact路径,返回的匹配码为1。
ContentUris:用于获取Uri路径后面的ID部分,它有两个比较实用的方法:
• withAppendedId(uri, id)用于为路径加上ID部分
• parseId(uri)方法用于从路径中获取ID部分
ContentResolver:当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法。 ContentResolver使用insert、delete、update、query方法,来操作数据。
四、ContentProvider示例程序
Manifest.xml中的代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".TestWebviewDemo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <data android:mimeType="vnd.android.cursor.dir/vnd.ruixin.login" /> </intent-filter> <intent-filter> <data android:mimeType="vnd.android.cursor.item/vnd.ruixin.login" /> </intent-filter> </activity> <provider android:name="MyProvider" android:authorities="com.ruixin.login" /> </application> |
需要在<application></application>中为provider进行注册!!!!
首先定义一个数据库的工具类:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class RuiXin { public static final String DBNAME = "ruixinonlinedb"; public static final String TNAME = "ruixinonline"; public static final int VERSION = 3; public static String TID = "tid"; public static final String EMAIL = "email"; public static final String USERNAME = "username"; public static final String DATE = "date"; public static final String SEX = "sex"; public static final String AUTOHORITY = "com.ruixin.login"; public static final int ITEM = 1; public static final int ITEM_ID = 2; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ruixin.login"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ruixin.login"; } |
- 然后创建一个数据库:
1234567891011121314151617181920212223242526272829
publicclassDBliteextendsSQLiteOpenHelper {publicDBlite(Context context) {super(context, RuiXin.DBNAME,null, RuiXin.VERSION);// TODO Auto-generated constructor stub}@OverridepublicvoidonCreate(SQLiteDatabase db) {// TODO Auto-generated method stubdb.execSQL("create table "+RuiXin.TNAME+"("+RuiXin.TID+" integer primary key autoincrement not null,"+RuiXin.EMAIL+" text not null,"+RuiXin.USERNAME+" text not null,"+RuiXin.DATE+" interger not null,"+RuiXin.SEX+" text not null);");}@OverridepublicvoidonUpgrade(SQLiteDatabase db,intoldVersion,intnewVersion) {// TODO Auto-generated method stub}publicvoidadd(String email,String username,String date,String sex){SQLiteDatabase db = getWritableDatabase();ContentValues values =newContentValues();values.put(RuiXin.EMAIL, email);values.put(RuiXin.USERNAME, username);values.put(RuiXin.DATE, date);values.put(RuiXin.SEX, sex);db.insert(RuiXin.TNAME,"",values);}}
- 接着创建一个Myprovider.java对数据库的接口进行包装:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
publicclassMyProviderextendsContentProvider{DBlite dBlite;SQLiteDatabase db;privatestaticfinalUriMatcher sMatcher;static{sMatcher =newUriMatcher(UriMatcher.NO_MATCH);sMatcher.addURI(RuiXin.AUTOHORITY,RuiXin.TNAME, RuiXin.ITEM);sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME+"/#", RuiXin.ITEM_ID);}@Overridepublicintdelete(Uri uri, String selection, String[] selectionArgs) {// TODO Auto-generated method stubdb = dBlite.getWritableDatabase();intcount =0;switch(sMatcher.match(uri)) {caseRuiXin.ITEM:count = db.delete(RuiXin.TNAME,selection, selectionArgs);break;caseRuiXin.ITEM_ID:String id = uri.getPathSegments().get(1);count = db.delete(RuiXin.TID, RuiXin.TID+"="+id+(!TextUtils.isEmpty(RuiXin.TID="?")?"AND("+selection+')':""), selectionArgs);break;default:thrownewIllegalArgumentException("Unknown URI"+uri);}getContext().getContentResolver().notifyChange(uri,null);returncount;}@OverridepublicString getType(Uri uri) {// TODO Auto-generated method stubswitch(sMatcher.match(uri)) {caseRuiXin.ITEM:returnRuiXin.CONTENT_TYPE;caseRuiXin.ITEM_ID:returnRuiXin.CONTENT_ITEM_TYPE;default:thrownewIllegalArgumentException("Unknown URI"+uri);}}@OverridepublicUri insert(Uri uri, ContentValues values) {// TODO Auto-generated method stubdb = dBlite.getWritableDatabase();longrowId;if(sMatcher.match(uri)!=RuiXin.ITEM){thrownewIllegalArgumentException("Unknown URI"+uri);}rowId = db.insert(RuiXin.TNAME,RuiXin.TID,values);if(rowId>0){Uri noteUri=ContentUris.withAppendedId(RuiXin.CONTENT_URI, rowId);getContext().getContentResolver().notifyChange(noteUri,null);returnnoteUri;}thrownewIllegalArgumentException("Unknown URI"+uri);}@OverridepublicbooleanonCreate() {// TODO Auto-generated method stubthis.dBlite =newDBlite(this.getContext());// db = dBlite.getWritableDatabase();// return (db == null)?false:true;returntrue;}@OverridepublicCursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {// TODO Auto-generated method stubdb = dBlite.getWritableDatabase();Cursor c;Log.d("-------", String.valueOf(sMatcher.match(uri)));switch(sMatcher.match(uri)) {caseRuiXin.ITEM:c = db.query(RuiXin.TNAME, projection, selection, selectionArgs,null,null,null);break;caseRuiXin.ITEM_ID:String id = uri.getPathSegments().get(1);c = db.query(RuiXin.TNAME, projection, RuiXin.TID+"="+id+(!TextUtils.isEmpty(selection)?"AND("+selection+')':""),selectionArgs,null,null, sortOrder);break;default:Log.d("!!!!!!","Unknown URI"+uri);thrownewIllegalArgumentException("Unknown URI"+uri);}c.setNotificationUri(getContext().getContentResolver(), uri);returnc;}@Overridepublicintupdate(Uri uri, ContentValues values, String selection,String[] selectionArgs) {// TODO Auto-generated method stubreturn0;}}最后创建测试类:
123456789101112131415161718192021222324252627282930publicclassTestextendsActivity {/** Called when the activity is first created. */privateDBlite dBlite1 =newDBlite(this);;privateContentResolver contentResolver;publicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//先对数据库进行添加数据dBlite1.add(email,username,date,sex);//通过contentResolver进行查找contentResolver = TestWebviewDemo.this.getContentResolver();Cursor cursor = contentResolver.query(RuiXin.CONTENT_URI,newString[] {RuiXin.EMAIL, RuiXin.USERNAME,RuiXin.DATE,RuiXin.SEX },null,null,null);while(cursor.moveToNext()) {Toast.makeText(TestWebviewDemo.this,cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL))+" "+ cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME))+" "+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE))+" "+ cursor.getString(cursor.getColumnIndex(RuiXin.SEX)),Toast.LENGTH_SHORT).show();}startManagingCursor(cursor);//查找后关闭游标}}注:上面是在一个程序中进行的测试,也可以再新建一个工程来模拟一个新的程序,然后将上面查询的代码加到新的程序当中!这样就模拟了contentprovider的数据共享功能了!
新建个工程:TestProvider
创建一个测试的activity123456789101112131415161718192021222324252627publicclassTestextendsActivity {/** Called when the activity is first created. */privateContentResolver contentResolver;publicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//通过contentResolver进行查找contentResolver = TestWebviewDemo.this.getContentResolver();Cursor cursor = contentResolver.query(RuiXin.CONTENT_URI,newString[] {RuiXin.EMAIL, RuiXin.USERNAME,RuiXin.DATE,RuiXin.SEX },null,null,null);while(cursor.moveToNext()) {Toast.makeText(TestWebviewDemo.this,cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL))+" "+ cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME))+" "+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE))+" "+ cursor.getString(cursor.getColumnIndex(RuiXin.SEX)),Toast.LENGTH_SHORT).show();}startManagingCursor(cursor);//查找后关闭游标}}运行此程序就能实现共享数据查询了!
注:新建的程序中的manifest.xml中不需要对provider进行注册,直接运行就行,否则会报错!
contentprovider的学习实例总结的更多相关文章
- 一、Android四大框架之ContentProvider的学习与运用,实现SQLite的增删改查。
本文系原创博客,文中不妥烦请指出,如需转载摘要请注明出处! ContentProvider的学习与运用 Alpha Dog 2016-04-13 10:27:06 首先,项目的地址:https:// ...
- Ant学习实例
ant 目录(?)[+] Ant学习实例 安装Ant 基础元素 project元素 target元素 property元素 完整示例 Ant学习实例 1.安装Ant 先从http://ant. ...
- Android ContentProvider 简单学习
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据.以前我们学习过文件的操作模式,通过指定文件的操作模式为Context.MODE_WORL ...
- zTree学习实例
今天做完一个zTree的实例,供有需要的学习! 效果图如下:
- (转)jQuery插件编写学习+实例——无限滚动
原文地址:http://www.cnblogs.com/nuller/p/3411627.html 最近自己在搞一个网站,需要用到无限滚动分页,想想工作两年有余了,竟然都没有写过插件,实在惭愧,于是简 ...
- jQuery插件编写学习+实例——无限滚动
最近自己在搞一个网站,需要用到无限滚动分页,想想工作两年有余了,竟然都没有写过插件,实在惭愧,于是简单学习了下jQuery的插件编写,然后分享出来. 先说下基础知识,基本上分为两种,一种是对象级别的插 ...
- WCF通信简单学习实例
最近在学习WCF通信,自己简单做个实例分享一下,环境是VS2015,使用的项目都是WPF的项目,其实大家用Winform或者Web项目也可以,都可以用的. 一.服务器端 1.创建WCF服务 服务名为W ...
- React入门最好的学习实例-TodoList
前言 React 的核心思想是:封装组件,各个组件维护自己的状态和 UI,当状态变更,自动重新渲染整个组件. 最近前端界闹的沸沸扬扬的技术当属react了,加上项目需要等等原因,自己也决定花些时间来好 ...
- Spring Security3学习实例
Spring Security是什么? Spring Security,这是一种基于Spring AOP和Servlet过滤器的安全框架.它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理 ...
随机推荐
- unity3d 日志捕捉
public class Test : MonoBehaviour { public string output = ""; public string stack = " ...
- ■Ascii逐字解码法注入,mysql5.0一下版本手工注入
/*By:珍惜少年时*/ 逐字解码法,不一定非要猜字段内容.库名,表名,字段,data,都能猜. 环境过滤了select.union(mysql5.0以下的版本就不支持union所以也可以用此方法), ...
- Android mtk单路录音问题
在单路录音中,有两种情况导致底层录音资源被占用的问题: 1 开启vmLog后,拨打一个电话,挂断电话.如果挂断电话后,没有关闭vmlog进程,则会导致其它AP 无法得到底层的录音资源,从而无法录音. ...
- 【Python】Django 聚合 Count与Sum用法,注意点
代码示例: from django.db.models import Sum, Count #alarm_sum_group_items = models.FILE_PROTECT_ALARM.obj ...
- Java 7 的7个新特性
1.对集合类的语言支持:(??) 2.自动资源管理: 3.改进的通用实例创建类型推断:(??) 4.数字字面量下划线支持:(√) 5.switch中使用string:(√) 6.二进制字面量:(√) ...
- Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- TCP/IP WebSocket MQTT
http://www.cnblogs.com/shanyou/p/4085802.html TCP/IP, WebSocket 和 MQTT
- location 、history
location.href= location.reload() history.go() 0 1 -1 history.back() history.forward() history.le ...
- 16.O(logn)求Fibonacci数列[Fibonacci]
[题目] log(n)时间Fib(n),本质log(n)求a^n. [代码] C++ Code 12345678910111213141516171819202122232425262728293 ...
- web开发中目录路径问题的解决
web开发当中,目录路径的书写是再常用不过了,一般情况下不会出什么问题,但是有些时候出现了问题却一直感到奇怪,所以这里记录一下,彻底解决web开发中路径的问题,开发分为前端和服务端,那么就从这两个方面 ...