一、内容提供器
使用内容提供器来共享数据可以精确的进行控制,哪些数据可以共享,哪些数据不可以共享内容提供器有两种用法:(1)使用现有的内容提供器来读取和操作相应程序中的数据;(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/table1和com.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部分描述urifrom table_name指定查询某个应用程序下的某一张表projectionselect colum1,column2指定查询的列名selectionwhere column = value指定where的约束条件selectionArgs为where中的占位符提供具体的值orderByorder 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"});
三、源码:
:https://blog.csdn.net/weixin_44630050博客园:https://www.cnblogs.com/ruigege0000/欢迎关注微信公众号:傅里叶变换,个人账号,仅用于技术交流
转载请注明原文地址:https://blackberry.8miu.com/read-45739.html