zoukankan      html  css  js  c++  java
  • Android连载37-跨程序共享数据

    一、内容提供器

    • 使用内容提供器来共享数据
    • 可以精确的进行控制,哪些数据可以共享,哪些数据不可以共享
    • 内容提供器有两种用法:(1)使用现有的内容提供器来读取和操作相应程序中的数据;(2)创建自己的内容提供器给我们的程序的数据提供外部访问接口

    二、ContentResolver的基本用法

    • 获取ContentResolver实例的方法: new Context().getContentResolver()
    • 该实例提供了一系列方法insert(),update(),delete(),query()用于CRUD操作
    • 这些成员方法在参数上与SQLiteDatabase实例有一些不同
    • 表名参数变成了Uri参数(内容URI)
    • URI有连部分组成:权限和路径
    • 权限用于不同的程序来进行区分的,都采用程序包命名的方式,比如某个程序包为com.example.app那么该程序对应的权限可以命名为com.example.app.provide
    • 路径则是用于对同一个应用程序中的不同的表进行区分的,通常会添加到权限后面,比如一个程序中含有两个表table1和table2,那么可以将路径分别命名为/table1和/table2。然后进行二者组合,内容Url变成了com.example.app.provider/table1com.example.app.provider/table2
    • 还需要在头部加上协议content://com.example.app.provider/table1
    • 对于这个字符串我们需要解析为Uri对象才能作为参数传入
    Uri uri = Uri.parse("content://com.example.app.provider/table1");
    • 查询代码如下
    Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
    • 这些参数我们做一个对比就一目了然了
    query()方法参数 对应SQL部分 描述
    uri from table_name 指定查询某个应用程序下的某一张表
    projection select colum1,column2 指定查询的列名
    selection where column = value 指定where的约束条件
    selectionArgs 为where中的占位符提供具体的值
    orderBy order by column1,column2 指定查询结果的排序方式
    • 查询后返回一个Cursor对象,接下来的我们将数据从Cursor对象中逐个读取出来,读取的思路仍然是通过移动游标的位置来进行遍历Cursor的所有行,然后在取出每一行中相应列的数据
    if(cursor != null ){
     while(cursor.moveToNext(){
      String column1 = cursor.getString(cursor.getColumnIndex("column1"));
      int column2 = cursor.getInt(cursor.getColumnIndex("column2"));
     }
     cursor.close();
    }
    • 剩下的增删该就不难了
    ContentValues values = new ContentValues();
    values.put("column1","text");
    values.put("column2","text");
    getContentResolver().insert(uri,values);
    • 上面时插入数据,下面来一个更新数据
    ContentValues values = new ContentValues();
    values.put("column1","");
    getContentResolver().update(uri,values,"column1 = ? and column2 = ?",new String[] {"text","1"});
    • 删除数据
    getContentResolver().delete(uri,"column2 = ?",new String[]{"1"});

    三、源码:

  • 相关阅读:
    OpenSSL: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
    Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
    for循环用了那么多次,但你真的了解它么?
    使用git克隆github上的项目失败,报错error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054
    idea修改svn地址
    Eureka服务注册中心错误:com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect
    Tensorflow学习资源
    编程工具使用技巧
    博客链接
    python学习笔记
  • 原文地址:https://www.cnblogs.com/ruigege0000/p/13783426.html
Copyright © 2011-2022 走看看