ContentResolver的基本用法
对于每个应用程序来说,如果想要访问内容提供器中共享的数据,就需要借助ContentResolver类,可以通过Context 中的getContextResolver()方法获取到该类的实例。Content中提供对数据进行的CRURD 和SQLiteDatabase中使用类似方法进行CRUD操作,只不过他们在方法参数上稍微有些不同
不同与SQLiteDatabase,ContenteResolver中的增删改查方法都是不接收表名参数的,而是使用一个Uri参数代替,该URI主要由两部分组成:authority和path。
authority(翻译:权威)是用于对不同的应用程序做区分的,一般为了避免冲突,都会采用程序包名的方式来命名
path 则是用于对同一个应用程序中不同的表做区分的 通常加在authority的后面
将authority和path进行组合,还需要在字符串的头部加上协议声明
-
内容URI最标准的格式写法如下:
content://com.example.app.provider/table1
content://com.example.app.provider/table1 -
得到内容URI字符串之后,我们还需要将它解析成Uri对象
Uri uri = Uri.parse(“content://com.example.app.provider/table1”)
- 只需要调用Uri.parse()方法, 之后就可以使用Uri对象查询
Cursor cursor = getContentResoler().query(
uri, projection,selection,selectionArgs,sortOrder);
###参数说明
quer()方法参数 | 对应SQL部分 | 描述 |
---|---|---|
uri | from table_name | 指定查询某个应用程序下的某一张表 |
projection | select column1,column2 | 指定查询的列名 |
selection | where column = value | 指定where的约束条件 |
selectionArges | - | 为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” , “”);
getContentResolver.update(uri,values,“column2 = ?”,new String[]{ “1” });