zoukankan      html  css  js  c++  java
  • Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

    (下面内容是阅读郭霖大神的《第一行代码》总结的)

    1 概述

    内容提供器是Android实现跨程序共享数据的标准方式。

    内容提供器的的使用方法有两种,

    一是使用已有的内容提供器对其他程序的数据进行访问;二是创建自己的内容提供器,将数据共享给其他程序。

    2 使用已有的内容提供器

    对于想访问内容提供器中共享数据的程序而言,ContentResolver类包含了它们想要进行的一切操作。

    2.1 ContentResolver类简介

    下面是Android API中对ContentResolver类的描述。

    要获取ContentResolver类的实例,我们可以使用context中的getContentResolver().

    和数据库操作一样,ContentResolver类也提供了对应增删改查的方法。

    2.2 Uri

    在介绍这些方法前我们需要了解内容URI。内容URI给内容提供器中的数据建立唯一标识(这部分取自郭大神的《第一行代码》)。

    它主要有两部分组成,权限(authority)和路径(path)。

    权限是用于对不同的应用程序做区分的,一般为了避免冲突,都会采用程序包名的方式来进行命名。

    比如某个程序的包名是com.example.app,那么该程序对应的权限就可以命名为com.example.app. provider。

    路径则是用于对同一应用程序中不同的表做区分的,通常都会添加到权限的后面。

    比如某个程序的数据库里存在两张表,table1和table2,这时就可以将路径分别命名为/table1和/table2。

    然后把权限和路径进行组合,内容URI就变成了com.example.app.provider/table1和com.example.app.provider/table2。

    不过,目前还很难辨认出这两个字符串就是两个内容URI,我们还需要在字符串的头部加上协议声明。因此,内容URI最标准的格式写法如下:

    content://com.example.app.provider/table1
    content://com.example.app.provider/table2

    得到内容URI,还需要将它解析成Uri的形式,才能作为参数,传入ContentResolve类中对应的增删改查的方法。

    解析URI的方法非常简单

    Uri uri = Uri.parse("content://com.example.app.provider/table1")

    2.3 ContentResolver类中的增删改查

    增:

    ContentValues values = new ContentValues();
    values.put("name","张三");
    values.put("age",27);
    getContentResolver().insert(uri, values);

    删:

    getContentResolver().delete(uri, "name = ?", new String[] { "张三" });

    改:

     

    ContentValues values = new ContentValues();
    values.put("name","李四");
    values.put("age",29);
    getContentResolver().update(uri,values,"name = ? and age = ?",
        new String[] = {"张三","28"});

    查:

    Cursor cursor = getContentResolver().query(uri,null, null, null, null);

    掌握上面的几个方法,我们就可以使用内容提供器对其他程序共享的数据进行操作了。

  • 相关阅读:
    网速问题?更换国内源吧!
    NES像素风格的Raspberry
    dalao自动报表邮件2.0
    大佬要我写自动邮件报表系统
    扬帆起航
    Linux下安装与配置tomcat集群+负载均衡
    centos配置ssh和ftp服务
    tomcat中server.xml配置详解
    设置windows 宿主计算机和VMware虚拟机共享文件夹
    Redhat6 yum 安装与配置
  • 原文地址:https://www.cnblogs.com/cuglkb/p/6518837.html
Copyright © 2011-2022 走看看