跨程序提供及获取内容

从别的程序获取数据

通过getContentResolver()方法获得ContentResolver实例

  • 增加数据

ContentValues values = new ContentValues();
values.put("column1", "text");
values.put("column2", 1);
getContentResolver().insert(uri, values);
  • 删除数据

getContentResolver().delete(uri, "column2 = ?", new String[] { "1" });
  • 更改数据

ContentValues values = new ContentValues();
values.put("column1", "");
getContentResolver().update(uri, values, "column1 = ? and column2 = ?", new
String[] {"text", "1"});
  • 查询数据

Cursor cursor = getContentResolver().query(
uri,    //uri对应的表
projection,    //指定查询的列名
selection,    //指定 where 的约束条件
selectionArgs,    //为 where 中的占位符提供具体的值
sortOrder);    //指定查询结果的排序方式
query()方法参数 对应 SQL 部分  描述
uri  from table_name  指定查询某个应用程序下的某一张表
projection  select column1, column2  指定查询的列名
selection  where column = value  指定 where 的约束条件
selectionArgs  -  为 where 中的占位符提供具体的值
orderBy  order by column1, olumn2  指定查询结果的排序方式



遍历 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();
    }

创造ContentProvider,给别的程序提供数据

新建 MyProvider 继承自 ContentProvider,重写6个方法

UriMatcher中提供了一个 addURI()方法,1.权限、2.路径、3.自定义代码

当调用 UriMatcher 的 match()方法时,就可以将一个 Uri 对象传入,返回值是某个能够匹配这个 Uri对象所对应的自定义代码,利用这个代码,我们就可以判断出调用方期望访问的是哪张表中的数据了

>MIME 类型
content://com.example.app.provider/table1 --------------------vnd.android.cursor.dir/vnd.com.example.app.provider.table1
content://com.example.app.provider/table1/1-------------------vnd.android.cursor.item/vnd.com.example.app.provider.table1

原文地址:https://www.cnblogs.com/cenzhongman/p/6392823.html