待续

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

posted on 2011-04-26 14:24  榆钱沽酒  阅读(999)  评论(0编辑  收藏  举报