/*********************************************************************************************************************/
作用:
实现跨进程的数据共享
注:内容提供者不仅可以在其他程序中使用,来修改或者查询数据,也可以在自己的程序内部使用来修改或者查询数据。例如,如果想要当数据库的内容发生改变时,做出相关的操作,这需要监听数据库内容的改变,这时候则可以使用自定义的内容提供者来修改数据,通过自定义的内容观察者来监听数据的改变,并作出相关的操作,具体操作见下面。
使用方法:
内容Uri,内容Uri由权限跟路径组成,权限一般是程序的包名,例如com.example.youxi,加上provider组成,例如com.example.youxi.provider,路径就是要访问的数据库表的名字,例如table1,加上路径com.example.youxi.provider/table1,为了区分出是内容Uri,还需要在前面加上content://,一个完成的内容Uri就可以写成:content://com.example.youxi.provider/table1,最后需要转换成Uri对象 Uri uri = Uri.parse("content://com.example.youxi.provider/table1");
权限是为了对不同的应用程序作区分的
路径是为了对程序中的不同的表作区分的
content://com.example.youxi.provider/table1 访问table1表中的全部数据
content://com.example.youxi.provider/table1/2 访问table1表中的id为2的记录
content://com.example.youxi.provider/table1/2/word 访问table1表中的id为2的记录的word字段
关于处理内容uri的几个常用方法:
ContentUris.withAppendId(Uri uri,long Id)
作用:给内容Uri添加id
示例:
Uri uri = Uri.parse("content://com.example.youxi.provider/table1");
uri = ContentUris.withAppendId(uri,2);
此时uri内容为为:content://com.example.youxi.provider/table1/2
ContentUris.parseId()
作用:取出内容Uri中的id
示例:
Uri uri = Uri.parse("content://com.example.youxi.provider/table1/2");
long id = ContentUris.parseId(uri);
此时id的值为2
ContentUris.parseId()跟Uri的getPathSegments.get(1);方法的作用是一致的
示例:
Uri uri = Uri.parse("content://com.example.youxi.provider/table1/2");
long id = uri.getPathSegments.get(1);
此时id的值为2
查询:
Cursor cursor = getContentResolver.query(uri,projection,selection,selectionArgs,sortOrder)
query方法参数 对应的SQL部分
描述
uri from table_name 指定查询某个应用程序下的某一张表
projection select column1, column2 指定查询的列名
selection where column = value 指定where的约束条件
selectionArgs --------- 为where中的占位符提供具体的内容
sortOrder order by column1,column2 指定查询结果的排序方式
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",1);
getContentResolver.insert(uri,values);
更新:
ContentValues values = new ContentValues();
values.put("column1","");
Uri uriReturn = getContentResolver.update(uri,values,"column1 = ?and column2 = ?",new String[]{"text","1"});
删除:
getContentResolver.delete(uri,"column2 = ?",new String[]{"1"});