`
_小菜鸟
  • 浏览: 34048 次
社区版块
存档分类
最新评论

我的android 第25天 - 使用ContentResolver操作ContentProvider中的数据

阅读更多

我的android 第25天 - 使用ContentResolver操作ContentProvider中的数据

 

当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法。 ContentResolver 类提供了与ContentProvider类相同签名的四个方法:

publicUri insert(Uri uri, ContentValuesvalues)

该方法用于往ContentProvider添加数据。

publicintdelete(Uri uri,String selection, String[] selectionArgs)

该方法用于从ContentProvider删除数据。

publicintupdate(Uri uri, ContentValuesvalues, String selection, String[] selectionArgs)

该方法用于更新ContentProvider中的数据。

publicCursor query(Uri uri,String[] projection, String selection, String[] selectionArgs,String sortOrder)

该方法用于从ContentProvider中获取数据。

这些方法的第一个参数为Uri,代表要操作的ContentProvider和对其中的什么数据进行操作,假设给定的是:Uri.parse(“content://cn.itcast.providers.personprovider/person/10”),那么将会对主机名为cn.itcast.providers.personprovider的ContentProvider进行操作,操作的数据为person表中id为10的记录。

使用ContentResolver对ContentProvider中的数据进行添加、删除、修改和查询操作:

ContentResolverresolver =  getContentResolver();

Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person");

//添加一条记录

ContentValuesvalues = new ContentValues();

values.put("name","itcast");

values.put("age",25);

resolver.insert(uri,values); 

//获取person表中所有记录

Cursorcursor = resolver.query(uri,null, null, null, "personiddesc");

while(cursor.moveToNext()){

  Log.i("ContentTest","personid="+cursor.getInt(0)+",name="+ cursor.getString(1));

}

//id1的记录的name字段值更改新为liming

ContentValuesupdateValues =new ContentValues();

updateValues.put("name","liming");

UriupdateIdUri = ContentUris.withAppendedId(uri,2);

resolver.update(updateIdUriupdateValues,null, null);

//删除id2的记录

UrideleteIdUri = ContentUris.withAppendedId(uri,2);

resolver.delete(deleteIdUri,null, null);

 

 

 

下载视频代码

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics