Content Providers

待续

Content Providers 是所有应用程序之间数据存储和检索的一个桥梁,作用是使得各个应用程序之间实现数据共享。

Cursor对象用于在结果集中前向或后向列举数据,Crusor对象只能用来读数据。

增加、修改、删除数据必须使用ContentResolver对象。

1. ContentResolver

应用可以通过一个唯一的ContentResolver接口来使用具体的某个ContentProviders。

通过getContentResolver()方法来获得一个ContentResolver对象,然后用ContentResolver提供的方法来操作Content Provider。

ContentResolver cr = getContentResolver();

 通常,对于每一种类型的ContentProvider只有一个实例,但这个实例可以与在不同的程序或进程中的多个ContentResolver对象进行通信。

进程之间的互动由ContentResolver和ContentProvider类处理的。

2. URI

每个Content Providers都会对外提供一个公共的URI(包装成Uri对象),如果应用程序有数据需要共享时,就需要使用Content Providers为这些

数据定义一个URI,然后其他的应用程序就可以通过Content Providers传入这个URI来对数据进行操作。

URI由3个部分组成:

"Content://" 、数据的路径、标识ID(可选)。

content://media/internal/images    (将返回设备上存储的所有图片)
content://contacts/people/5           (将返回ID=5的联系人记录)
content://contacts/people               (将返回设备所有联系人信息)

在andorid.provider包下提供了一系列的辅助类,其中包含了很多以类变量形式给出的查询字符串,如可以将第二个URI改写成以下形式

Uri person=ContentUris.withAppendedId(People.CONTENT_URI,5);

每个ContentResolver都把URI作为其第一个参数,它决定了ContentResolver将与哪一个Provider对话。

3. 查询数据

A.用ContentReslover.query()方法
B.用Activity.managedQuery()方法。 包含Cursor生命周期,当Activity暂停后,要使用Cursor必须通过Activity.startManagingCursor()方法重新启动。

Cursor cur = managedQuery(person, null, null, null);

String[] projection = new String[]{};        //需要获取的列
Uri contacts = People.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection,    // 返回指定列的数据
              null,                            // 返回所有行的数据
              null,                            //可选参数
              People.NAME + " ASC");  //按名字的省续排列

4. 修改数据

ContentResolver.update()方法

5. 添加数据

ContentResolver.insert()方法。

6. 删除数据

ContentResolver.delete()方法

7. 创建自己的Content Provider

转载于:https://www.cnblogs.com/topcoderliu/archive/2011/04/26/2029275.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值