使用ContentResolver操作ContentProvider中的数据

来源:互联网 发布:洛奇英雄传捏脸数据 编辑:程序博客网 时间:2024/06/05 04:50

使用ContentResolver操作ContentProvider中的数据

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

public Uri insert(Uri uri,ContentValues values)

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

public int delete(Uri uri,String selection, String[] selectionArgs)

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

public int update(Uri uri,ContentValues values, String selection, String[] selectionArgs)

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

public Cursor query(Uri uri,String[] projection, String selection, String[] selectionArgs, StringsortOrder)

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

 

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

 

使用ContentResolver操作ContentProvider中的数据

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

ContentResolver resolver=  getContentResolver();

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

//添加一条记录

ContentValues values = newContentValues();

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

values.put("age",25);

resolver.insert(uri,values);        

//获取person表中所有记录

Cursor cursor =resolver.query(uri, null, null, null, "personid desc");

while(cursor.moveToNext()){

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

}

//把id为1的记录的name字段值更改新为liming

ContentValues updateValues =new ContentValues();

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

Uri updateIdUri =ContentUris.withAppendedId(uri, 2);

resolver.update(updateIdUri,updateValues, null, null);

//删除id为2的记录

Uri deleteIdUri =ContentUris.withAppendedId(uri, 2);

resolver.delete(deleteIdUri,null, null);



0 0
原创粉丝点击