ContentResovler的基本用法

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部分描述
urifrom table_name指定查询某个应用程序下的某一张表
projectionselect column1,column2指定查询的列名
selectionwhere column = value指定where的约束条件
selectionArges-为where中的占位符提供具体的值
sortorderorder 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” });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bingeho

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值