Android ContentProvider 分析与应用(一)使用ContentProvider

来源:互联网 发布:loho眼镜怎么样 知乎 编辑:程序博客网 时间:2024/05/06 02:50

搞明白如何使用系统提供ContentProvider。会用系统提供的ContentProvider了,就知道能够给我们带来哪些功能。步骤非常简单。

        第一步:找到需要调用的ContentProvider的uri。

        第二步:使用ContentResolver对象,调用query(delete;insert;update)方法,获取数据即可。

以查找手机联系人为例:

第一步:找到目标uri;

    因为我们是要找到手机联系人的uri,那么我们知道,系统给我们提供了Contacts(联系人)类。我们打开Contacts的源码看看,发现在这个类里封装了非常多的常量。其中People是我们需要找的目标,打开来看看。代码较多,我截取一部分重点的。

  1.    public static final class People implements BaseColumns, PeopleColumns,
  2.            PhonesColumns, PresenceColumns {
  3.        private People() {}
  4.        /**
  5.         * The content:// style URL for this table
  6.         * @deprecated see {@link android.provider.ContactsContract}
  7.         */
  8.        @Deprecated
  9.        public static final Uri CONTENT_URI =
  10.            Uri.parse("content://contacts/people");
  11.        public static final Uri CONTENT_FILTER_URI =
  12.            Uri.parse("content://contacts/people/filter");
  13.        public static final Uri DELETED_CONTENT_URI =
  14.            Uri.parse("content://contacts/deleted_people");
  15.        public static final Uri WITH_EMAIL_OR_IM_FILTER_URI =
  16.            Uri.parse("content://contacts/people/with_email_or_im_filter");
  17.        @Deprecated
  18.        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/person";
  19.        @Deprecated
  20.        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/person";
  21.        @Deprecated
  22.        public static final String DEFAULT_SORT_ORDER = People.NAME + " ASC";

我们可以看到uri这么多那个是我们想要的呢(妹子那么多,那个是你的)?从字面上我们知道,CONTENT_URI就是我们想要的那个。第一步完成。

第二步:创建ContentResolver对象,调用query方法,获取数据。代码如下。

  1. private void query() {
  2.    Uri url = Contacts.People.CONTENT_URI;
  3.    Cursor cursor = this.getContentResolver().query(url, null, null, null, null);
  4.    cursor.moveToFirst();
  5.    while(!cursor.isAfterLast()) {
  6.        String name = cursor.getString(cursor.getColumnIndex(People.NAME));
  7.        String number = cursor.getString(cursor.getColumnIndex(People.NUMBER));
  8.        Log.e("test ", "name: " + name);
  9.        Log.e("test ", "number: " + number);
  10.        cursor.moveToNext();
  11.    }
  12.    cursor.close();
  13. }

通过ContentResolver对象调用query方法,获取到People表的集合数据。通过moveToFirst方法,让游标进入表,并从首行开始通过while循坏查询单个People。通过cursor.getColumnIndex(People.NAME))获取联系人名,手机号码等。通过cursor.moveToNext()进入下一行查询,如此这般,手机联系人中的人名和手机号码都获取到了。结束while循环后,记得关闭cursor。完成了,是不是非常非常简单?delete;insert;update的操作依次类推了。




总结:ContentResolver是可以提供给我们跨应用获取数据的。也就是说我们可以从b应用查询a应用的数据。例如我们在demo中可以查询系统手机联系人信息。那么在我们的应用中可不可以通过ContentResolver提供给activity查询数据呢?答案是肯定的。那么我们就需要自定义ContentResolver并提供uri就可以了,至于delete;insert;update;query我们都不必完善,增删改查交给b应用自己完善,在a应用中只需要把相关常量提供好即可。例如Contacts的做法我觉得就很不错。好了,下一篇我们就模仿ContactsContentResolver,自定义一个ContentResolver给我们的控制层使用。

0 0