Android连载37-跨程序共享数据

1、内容提供器

  • 使用内容提供器来共享数据
  • 能够精确的进行控制,哪些数据能够共享,哪些数据不能够共享
  • 内容提供器有两种用法:(1)使用现有的内容提供器来读取和操做相应程序中的数据;(2)建立本身的内容提供器给咱们的程序的数据提供外部访问接口

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"});

3、源码:

相关文章
相关标签/搜索