访问其他程序中的数据

ContentResolver()中的增删改查方法不接收表名参数,而使用的是一个Uri参数,这个参数被称为内容URl。内容URl给内容提供器中的数据建立了唯一标识符,它主要由两部分组成:authority和path。authority是用于对不同的应用程序做区分,一般采用程序包名的方式进行命名,比如一个程序的包名为com.example.app,那么该程序的authority就可以命名为com.example.app.provider。path是用于对同一程序中不同的表做区分的,通常添加到authority后面。比如某个程序的数据库里面存在两张表,table1和table2,这时可以将path分别命名为/table1和/table2,然后将authority和path进行组合。除此以外,要辨别它是内容的URl,所以还要在字符串的头部加上协议声明“content://”。综上所述,内容URl最标准的写法如下:

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

得到内容URl字符串之后,我们需要将它解析成Uri对象才可以作为参数传入,代码如下:
Uri uri = Uri.parse("content://com.example.app.provider/table1")

查询

Cursor cursor = getContentResolver().query(
    uri,            //查询某张表
    projection,     //指定查询的列名
    selection,      //指定where的约束条件
    selectionArgs,  //为where中的占位符提供具体的值
    sortOrder       //指定查询结果的排序方式
)

查询完成后返回的是一个Cursor对象,这时我们可以将数据从Cursor对象中逐个读取出来。

if (cursor ! = null) {
  while(cursor.moveToNext(){
     String column1 = cursor.getString(cursor.getColumnIndex("column1"));
     String column2 = cursor.getString(cursor.getColumnIndex("column2"));
   }
   cursor.close();
}

增加

ContentValues contentValues = new ContentValues();
contentValues.put("column1", "text");
contentValues.put("column2", 1);
getContentResolver().insert(uri, contentValues);

修改

ContentValues contentValues = new ContentValues();
contentValues.put("column1", "");
getContentResolver().update(uri,contentValues,"column1=? and column2 =?",new String[]{"text","1"});

删除
getContentResolver().delete(uri,"column2 = ?",new String[]{"1"});

原文地址:https://www.cnblogs.com/ngy-liupeng/p/15168508.html