您的位置:首页 > 其它

添加、更新和删除内容

2009-08-07 17:09 288 查看
在Content Provider上执行交互,通过调用ContentResolver对象的delete、update和insert方法。

Insert

ContentResolver提供了两个插入新的记录的方法——insert和bulkInsert。两个方法都接受你想添加的项目类型的URI;前者接受单一的ContentValues对象,后者接受一个数组。

简单的insert方法会返回新添加的记录的URI,而bulkInsert会返回成功添加的项目个数。

下面的代码片段显示了如何使用insert方法和bulkInsert方法:

// Create a new row of values to insert.

ContentValues newValues = new ContentValues();

// Assign values for each row.

newValues.put(COLUMN_NAME, newValue);

[ ... Repeat for each column ... ]

Uri myRowUri = getContentResolver().insert(MyProvider.CONTENT_URI, newValues);

// Create a new row of values to insert.

ContentValues[] valueArray = new ContentValues[5];

// TODO: Create an array of new rows

int count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI, valueArray);

Delete

为了通过ContentResolver来删除一条记录,调用delete,传入你想删除的行的URI。可变通的地方,你可以指定一个where语句来删除多个行。两种技巧都在下面的片段中显示:

// Remove a specific row.

getContentResolver().delete(myRowUri, null, null);

// Remove the first five rows.

String where = “_id < 5”;

getContentResolver().delete(MyProvider.CONTENT_URI, where, null);

Update

通过在ContentResolver上调用update方法来对Content Provider进行更新。update方法需要目标Content Provider的URI,一个更新了数据的ContentValues对象,还有一个where语句来指定哪些行要被更新。

当执行时,与where语句匹配的行都会使用传入的ContentValues对象进行更新,并返回成功更新的行的数目。

// Create a new row of values to insert.

ContentValues newValues = new ContentValues();

// Create a replacement map, specifying which columns you want to

// update, and what values to assign to each of them.

newValues.put(COLUMN_NAME, newValue);

// Apply to the first 5 rows.

String where = “_id < 5”;

getContentResolver().update(MyProvider.CONTENT_URI, newValues, where, null);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐